用类实现自定义主件
from tkinter import * class HelloButton(Button): def __init__(self, parent=None, **config): # add callback method Button.__init__(self, parent, **config) # and pack myself self.pack() # could config style too self.config(command=self.callback) def callback(self): # default press action print(‘Goodbye world...‘) # replace in subclasses self.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 Frame def __init__(self, parent=None): Frame.__init__(self, parent) # do superclass init self.pack() self.data = 42 self.make_widgets() # attach widgets to self def make_widgets(self): widget = Button(self, text=‘Hello frame world!‘, command=self.message) widget.pack(side=LEFT) def message(self): self.data += 1 print(‘Hello frame world %s!‘ % self.data) if __name__ == ‘__main__‘: Hello().mainloop()
独立的容器类
from tkinter import * class HelloPackage: # not a widget subbclass def __init__(self, parent=None): self.top = Frame(parent) # embed a Frame self.top.pack() self.data = 0 self.make_widgets() # attach widgets to self.top def 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 += 1 print(‘Hello number‘, self.data) if __name__ == ‘__main__‘: HelloPackage().top.mainloop()
原文:http://www.cnblogs.com/zhuweiblog/p/5245683.html