fromTkinterImport*#Get widget Classes fromTkinter.messageboxImportAskokcancel#get canned std dialogclassQuitter (Frame):#Subclass Our GUI def __init__(Self, Parent=none):#Constructor MethodFrame.__init__(self, parent) Self.pack () widget= Button (self, text='Quit', command=self.quit) widget.pack (Side=left, Expand=yes, fill=BOTH)defQuit (self): ans= Askokcancel ('Verify Exit',"really quit?") ifans:Frame.quit (self)if __name__=='__main__': Quitter (). Mainloop ()
Select Window Color
fromTkinterImport* fromTkinter.colorchooserImportAskcolordefSetbgcolor (): (triple, hexstr)=Askcolor ()ifhexstr:Print(HEXSTR)Print(triple) Push.config (BG=hexstr) Root=Tk () Push= Button (Root, text='Set Background Color', command=setbgcolor) push.config (height=3, font= (' Times', 20,'Bold')) Push.pack (expand=yes, fill=BOTH) Root.mainloop ()
Binding events
fromTkinterImport*defshowposevent (event):Print('widget=%s x=%s y=%s'%(Event.widget, Event.x, Event.y))defshowallevent (event):Print(Event) forattrinchDir (event):if notAttr.startswith ('__'): Print(attr,'=', GetAttr (event, attr))defonKeyPress (event):Print('Got Key Press:', Event.char)defOnarrowkey (event):Print('Got up ARROW key Press')defOnreturnkey (event):Print('Got return key Press')defOnleftclick (event):Print('Got left mouse button click:', end=' ') showposevent (event)defOnrightclick (event):Print('Got right mouse button click:', end=' ') showposevent (event)defOnmiddleclick (event):Print('Got middle mouse button click:', end=' ') showposevent (event) showallevent (event)defOnleftdrag (event):Print('Got left mouse button drag:', end=' ') showposevent (event)defOndoubleleftclick (event):Print('Got double left mouse click', end=' ') showposevent (event) tkroot.quit () Tkroot=Tk () Labelfont= ('Courier', 20,'Bold')#family, size, styleWidget = Label (Tkroot, text='Hello bind World') widget.config (BG='Red', Font=labelfont)#red background, large fontWidget.config (height=5, width=20)#Initial Size:lines,charsWidget.pack (Expand=yes, fill=BOTH) Widget.bind ('<Button-1>', Onleftclick)#mouse button clicksWidget.bind ('<Button-3>', Onrightclick) Widget.bind ('<Button-2>', Onmiddleclick)#Middle=both on some miceWidget.bind ('<Double-1>', Ondoubleleftclick)#Click Left twiceWidget.bind ('<B1-Motion>', Onleftdrag)#Click Left and moveWidget.bind ('<KeyPress>', onKeyPress)#All keyboard PressesWidget.bind ('<Up>', Onarrowkey)#arrow Button pressedWidget.bind ('<Return>', Onreturnkey)#return/enter Key pressedWidget.focus ()#or bind keypress to TkrootTkroot.title ('Click Me') Tkroot.mainloop ()
Tkinter notes Four