PYTHON GUI 编程2
大家好,我们继续来探讨python GUI编程中使用tkinter包的第三个步骤。
定义事件处理程序
构建GUI应用的下一步是定义窗口使用的事件。控件可以产生事件,例如当用户单击按钮时,并且使用command参数可以指定当python检测到事件时应该调用的方法名称。例如,我们要把按钮绑定到一个事件方法上,代码可编写为:
def creat_widgets(self):
self.button1 = Button(self,text = 'Submit',
command = self.display)
self.button1.grid(row = 1,column = 0,
sticky = W)
def display(self):
print('The button clicked in the window')
create_widgets()方法创建一个按钮显示在窗口区域,Button类的构造函数设置了command参数是self.display,这指向类中的display()方法。
这时,我们可以编写一个完整的GUI程序了。
from tkinter import *
class Application(Frame):
'''Built the basic window frame template'''
def __init__(self,master):
super(Application,self).__init__(master)
self.grid()
self.create_widgets()
def create_widgets(self):
self.label1 = Label(self,
text = ('Welcome to my window!')
self.label1.grid(row = 0,column = 0,sticky = W)
self.button1 = Button(self,text = 'Submit',
command = self.display)
self.button1.grid(row = 1,column = 0,
sticky = W)
def display(self):
'''Event handler for the button'''
print('The button clicked in the window')
root = Tk()
root.title('Test Button events')
root.geometry('300x100')
app = Application(root)
app.mainloop()
代码运行结果
当你点击Submit按钮时,在窗口中会出现display()方法中print的内容。
到这里,我们已经学会使用tkinter包创建一个简单GUI应用,大家快去试一试吧