160 likes | 532 Views
Graphics Programming with Python. Many choices. Python offers us several library choices: Tkinter WxPython PyQt PyGTK Jython And others. Tkinter. Tkinter is the 'standard' library for programming Python GUI's because it is: Accessible (lightweight and easy-to-use)
E N D
Many choices • Python offers us several library choices: • Tkinter • WxPython • PyQt • PyGTK • Jython • And others...
Tkinter • Tkinter is the 'standard' library for programming Python GUI's because it is: • Accessible (lightweight and easy-to-use) • Portable (runs cross-platform) • Available (standard module in the Python library) • Well-documented • Python's interface to tk, GUI library for Tcl
Code Example • from Tkinter import Label • widget = Label(None, text='Hello World!') • widget.pack() • widget.mainloop()
Hello World! • Create new label, placed in highest level window • Default arrangement (top side) • mainloop() shows window and starts event handling
Packing • pack() method invokes geometry manager which controls layout • 'widgets' are arranged within containers (window, frame, etc.) • Containers within containers → hierarchical GUI display • Grid geometry as alternative
Code Example • from Tkinter import * • Label(text='Hello World!').pack(expand=YES, fill=BOTH) • mainloop()
Resizing • Windows can be resized by default • Expand causes all available space within a container to be allocated to this widget • As consequence, centers widget if alone • Fill makes the widget physically stretch to fill this space (BOTH means both horizontally(X) and vertically (Y))
Code Example • from Tkinter import * • widget = Label() • widget['text'] = 'Hello World!' • widget.pack(side=TOP) • mainloop()
Code Example • from Tkinter import * • root = tk() • widget = Label(root) • widget.config(text='Hello World!') • widget.pack(side=TOP, expand=YES) • root.title('MyWindow') • root.mainloop()
Code Example • import sys • from Tkinter import * • widget = Button(None, text='Goodbye!', command=sys.exit) • widget.pack(side=RIGHT) • widget.mainloop()
Binding Events • Def haha(): • print 'Hahahahaha!' • widget = Button(None, text='HAHA') • widget.bind('<Button-1>', haha) • Now, clicking this button(left) will cause your computer to laugh at you