用类实现自定义主件
from tkinter import *class HelloButton(Button):def __init__(self, parent=None, **config): # add callback methodButton.__init__(self, parent, **config) # and pack myselfself.pack() # could config style tooself.config(command=self.callback)def callback(self): # default press actionprint('Goodbye world...') # replace in subclassesself.quit()if __name__ == '__main__':HelloButton(text='Hello subclass world').mainloop()
Button(win, text='Hello', command=greeting).pack(side=LEFT, anchor=N)Label(win, text='Hello container world').pack(side=TOP)Button(win, text='Quit', command=win.quit).pack(side=RIGHT)
继承类部件
from tkinter import *class Hello(Frame): # an extended Framedef __init__(self, parent=None):Frame.__init__(self, parent) # do superclass initself.pack()self.data = 42self.make_widgets() # attach widgets to selfdef make_widgets(self):widget = Button(self, text='Hello frame world!', command=self.message)widget.pack(side=LEFT)def message(self):self.data += 1print('Hello frame world %s!' % self.data)if __name__ == '__main__': Hello().mainloop()
独立的容器类
from tkinter import *class HelloPackage: # not a widget subbclassdef __init__(self, parent=None):self.top = Frame(parent) # embed a Frameself.top.pack()self.data = 0self.make_widgets() # attach widgets to self.topdef make_widgets(self):Button(self.top, text='Bye', command=self.top.quit).pack(side=LEFT)Button(self.top, text='Hye', command=self.message).pack(side=RIGHT)def message(self):self.data += 1print('Hello number', self.data)if __name__ == '__main__': HelloPackage().top.mainloop()