Tkinter(T-K-Inter)模块包含建立各类GUI(图形用户界面设计)的类。Tk建立一个放置GUI小构件的窗口(便可视化组件)。python
from tkinter import * # 导入tkinter模块 window = Tk() # 建立一个窗口(父容器) label = Label(window, text="Welcome to Python") # 建立一个标签(小构件类,其第一个参数永远是父容器) button = Button(window, text="Click Me") # 建立一个按钮 label.pack() # 把标签放在窗口中(使用一个包管理器,将label放在容器中) button.pack() # 把按钮放在窗口中 window.mainloop() # 建立一个事件循环,这个事件循环持续处理事件,直到关闭主窗口
一个Tkinter小构件能够与一个函数绑定,当事件发生时被调用函数
from tkinter import * class ProcessButtonEvent: def __init__(self): window = Tk() okButton = Button(window, text="OK", fg="red", command=self.processOk) # 将okButton绑定到processOK函数,当按钮被单击时,这个函数将被调用。fg 指定按钮前景色,默认为黑色 cancelButton = Button(window, text="CANCEL", fg="red", bg="yellow", command=self.processCancel) #bg 指定按钮背景色,默认为灰色 okButton.pack() cancelButton.pack() window.mainloop() def processOk(self): print("Ok button is clicked") def processCancel(self): print("Cancel button is clicked") ProcessButtonEvent()
程序定义了两个函数,processOk和processCancel,当建立这些函数时,这些函数被绑定到按钮。这些函数被称为回调函数或处理器。oop
定义一个类来建立GUI和处理GUI事件有两个优势。首先,未来能够重复使用这个类;其次,将全部函数定义为方法可让它们访问类中的实例数据域。spa