Tkinter - Guis in Python: Dan Fleck Cs112 George Mason University
Tkinter - Guis in Python: Dan Fleck Cs112 George Mason University
What is it?
! Tkinter is a Python interface to the Tk graphics library.
!Tk is a graphics library widely used and available everywhere
A Label is a widget that holds text This one has a parent of root That is the mandatory first argument to the Labels constructor
root.mainloop() Windows go into an event loop where they wait for things to
happen (buttons pushed, text entered, mouse clicks, etc) or Windowing operations to be needed (redraw, etc..). You must tell the root window to enter its event loop or the window wont be displayed!
Class
Objects
! Again Objects combine data and operations ! For example, you could create a Car class that has:
!data amount of gas in tank, odometer reading, year built, etc !operations start car, apply brakes, start windshield wipers, etc
Do all objects of class Car have the same data values? No! Amount of gas in the tank is different for each object
Tkinter objects
! Label is a class, w is an object
!w = Label(root, text="Hello, world!") !Call the pack operation:
Build it (called instantiation)
! w.pack() ! Hint: An operation is just a function nothing more, nothing less.. it is just defined inside the class to act upon the objects current data. Objects usually hide their data from anyone else and let other programmers access the data only through operations. (This is an OO concept called encapsulation)
This says, whenever someone pushes the button, call the buttonPushed function. (Generically any function called by an action like this is a callback)
root = Tk() # Create the root (base) window where all widgets go w = Label(root, text="Hello, world!") # Create a label with words w.pack() # Put the label into the window myButton = Button(root, text="Exit",command=buttonPushed) myButton.pack() root.mainloop() # Start the event loop
Need later
def main(): Use the global root window global root root = Tk() # Create the root (base) window where all widgets go w = Label(root, text="Hello, world!") # Create a label with words w.pack() # Put the label into the window myButton = Button(root, text="Exit",command=buttonPushed) myButton.pack() root.mainloop() # Start the event loop main()
Calling this also ends the mainloop() function (and thus ends your program)
# Hold onto a global reference for the root window root = None # Hold onto the Text Entry Box also entryBox = None def buttonPushed(): global entryBox txt = entryBox.get() print "The text is:",txt def createTextBox(parent): global entryBox entryBox = Entry(parent) entryBox.pack() def main(): global root root = Tk() # Create the root (base) window where all widgets go myButton = Button(root, text="Show Text",command=buttonPushed) myButton.pack() createTextBox(root) root.mainloop() # Start the event loop main()
Call the get() operation on the entry box to get the text when button is pushed Create the global entry box!
#changeable_label.py # Use a StringVar to create a changeable label from Tkinter import * # Hold onto a global reference for the root window root = None # Changeable text that will go inside the Label myText = None count = 0 # Click counter def buttonPushed(): global myText
Set the text in the label (call set method with a def addTextLabel(root): global myText string actual parameter) myText = StringVar() Create a StringVar to hold text myText.set("") myLabel = Label(root, textvariable=myText) Link the label to the StringVar myLabel.pack()
def main(): global root root = Tk() # Create the root (base) window where all widgets go myButton = Button(root, text="Show Text",command=buttonPushed) myButton.pack() addTextLabel(root) root.mainloop() # Start the event loop main()
global count count += 1 myText.set("Stop your clicking, it's already been %d times!" %(count))
Layout management
! You may have noticed as we pack widgets into the window they always go under the previous widget ! What if we want to get them to go sideby-side or some other place? ! Most windowing toolkits have layout management systems to help you arrange widgets!
Layout management
! Youve been using one the packer is called when you pack() ! pack can have a side to pack on:
!myWidget.pack(side=LEFT) !this tells pack to put this widget to the left of the next widget !Lets see other options for pack at: !http://epydoc.sourceforge.net/stdlib/ Tkinter.Pack-class.html#pack
Pack Examples
#pack_sample.py from Tkinter import * # Hold onto a global reference for the root window root = None count = 0 # Click counter def addButton(root, sideToPack): global count name = "Button "+ str(count) +" "+sideToPack button = Button(root, text=name) button.pack(side=sideToPack) count +=1 def main(): global root root = Tk() # Create the root (base) window where all widgets go for i in range(5): addButton(root, TOP) root.mainloop() # Start the event loop main()
Pack Examples
#pack_sample.py from Tkinter import * # Hold onto a global reference for the root window root = None count = 0 # Click counter def addButton(root, sideToPack): global count name = "Button "+ str(count) +" "+sideToPack button = Button(root, text=name) button.pack(side=sideToPack) count +=1 def main(): global root root = Tk() # Create the root (base) window where all widgets go addButton(root, LEFT) # Put the left side of the next widget close to me addButton(root, BOTTOM) # Put bottom of next widget close to me addButton(root, RIGHT) # Put right of next widget close to me addButton(root, BOTTOM) # Put bottom of next widget close to me root.mainloop() # Start the event loop main()
Packing Frames
! Usually you cannot get the desired look with pack unless you use Frames ! Frame are widgets that hold other widgets. (Frames are parents). ! Usually root has Frames as children and Frames have widgets or more Frames as children.
Packing Frames
! Lets say you want this GUI
Packing Frames
! You know how to create any one area already. For example if I said create a window with a list of buttons arranged vertically you would do this:
!
! ! ! !
addButton(root, TOP) addButton(root, TOP) addButton(root, TOP) addButton(root, TOP) addButton(root, TOP)
Packing Frames
! To do that with a Frame you just do this instead: Create the frame like any other widget! ! ! ! ! ! frame1 = Frame(root) addButton(frame1 , TOP) addButton(frame1 , TOP) addButton(frame1 , TOP) addButton(frame1 , TOP)
! addButton(frame1 , TOP)
Packing Frames
! To do that with a Frame you just do this instead: ! Now, assuming you created the frames already: ! redFrame.pack(side=LEFT) ! brownFrame.pack(side=LEFT) ! topYellow.pack(side=TOP) ! green.pack(side=TOP) ! bottomYellow.pack(side=TOP) Who is the parent of the red and brown frames? Ans: The green frame!
Adding Menus
! A menu is simply another type of widget.
# create a toplevel menu menubar = Menu(root)
The menubar is a container for Menus
# create a pulldown menu, and add it to the menu bar filemenu = Menu(menubar) Create a single menu filemenu.add_command(label="Open", command=hello) filemenu.add_separator() Add a line separator in the menu filemenu.add_command(label="Exit,command=root.destroy) menubar.add_cascade(label="File", menu=filemenu) root.config(menu=menubar)
Call the hello function when the Open menu option is chosen
Call the root.destroy function when the Exit menu option is chosen Add the filemenu as a menu item under the menubar
Adding Menus
# create a toplevel menu menubar = Menu(root) # create a pulldown menu, and add it to the menu bar filemenu = Menu(menubar) filemenu.add_command(label="Open", command=hello) filemenu.add_separator() filemenu.add_command(label="Exit,command=root.destroy) menubar.add_cascade(label="File", menu=filemenu) root.config(menu=menubar)
Adding Sub-Menus
Adding sub-menus, is done by adding a menu to another menu instead of the menubar.
# Create another menu item named Hello helloMenu = Menu(menubar) helloMenu.add_command(label="Say hello", command=hello) menubar.add_cascade(label="Hello", menu=helloMenu) # Create a submenu under the Hello Menu subHello = Menu(helloMenu) # My parent is the helloMenu subHello.add_command(label="English", command=hello) # Menu Item 1 subHello.add_command(label="Spanish", command=hello) # Menu Item 2 subHello.add_command(label="Chinese", command=hello) # Menu Item 3 subHello.add_command(label="French", command=hello) # Menu Item 4 # Add sub menu into parent with the label International Hello helloMenu.add_cascade(label="International Hello", menu=subHello)
Showing Images
An image is just another widget. photo = PhotoImage(file=somefile.gif)
Note: Tkinter only supports GIF, PGM, PBM, to read JPGs you need to use the Python Imaging Library
im = PhotoImage(file='cake.gif') # Create the PhotoImage widget # Add the photo to a label: w = Label(root, image=im) # Create a label with image w.image = im # Always keep a reference to avoid garbage collection w.pack() # Put the label into the window
Showing Images
A Canvas is a container that allows you to show images and draw on the container. Draw graphs, charts, implement custom widgets (by drawing on them and then handling mouse-clicks). A canvas was the widget that Turtle Graphics uses to draw on! myCanvas = Canvas(root, width=400, height=200) myCanvas.create_line(0, 0, 200, 100) myCanvas.create_line(0, 100, 200, 0, fill="red", dash=(4, 4)) myCanvas.create_image(0, 0, anchor=NW, image=myPhotoImage) How to use a canvas: http://effbot.org/tkinterbook/canvas.htm
Capturing mouse-clicks
! To capture mouse events you can bind events to a widget.
!widget.bind(event, handler) !events can be:
! <Button-1>
! (1 is left mouse button, 2=right, 3=middle)
! <Double-Button-1> - double clicked button 1 ! <Enter> - mouse entered the widget ! <Leave> - mouse left the widget ! <Return> - user pressed enter key ! <key> (<a> for example) user pressed a
Capturing mouse-clicks
For example, to make a button beg to be clicked:
def mouseEntered(event): button = event.widget button.config(text = "Please Please click me") def mouseExited(event): button = event.widget button.config(text = "Logon") def main(): global root root = Tk() # Create the root (base) window where all widgets go b = Button(root, text="Logon") b.bind("<Enter>",mouseEntered) Step 1: Bind events b.bind("<Leave>",mouseExited) b.pack() root.mainloop() # Start the event loop main()
Step 2: Write functions to handle events. Notice: event object automatically passed into event handler!
to functions
Capturing mouse-clicks
def mouseEntered(event): button = event.widget button.config(text = "Please Please click me")
Notice how I say event.widget that is because all events store as data the widget that caused the event. In this case it is a button. (This again is because event is an object of class Event. That object stores data items one of which is named widget. Note: in the project you will need to bind left-button mouse events to the canvas and then look at the x,y location of the click. Is x,y stored in the event? Check the link below to see the names ot everything you can get from an event object just by saying: myVariable = event.attribute
http://www.pythonware.com/library/tkinter/introduction/events-and-bindings.htm
Common problem!
def main(): global root root = Tk() # Create the root (base) window where all widgets go b = Button(root, text="Logon") WARNING: When b.bind("<Enter>",mouseEntered) b.bind("<Leave>",mouseExited) b.pack() root.mainloop() # Start the event loop main()
you specify a function, you must NOT use parenthesis using parenthesis CALLS the function once.. you want to pass the function as a parameter!
! Many events you never see (window resized, iconified, hidden by another window and reshown) You can capture these events if desired, but Tkinter handles them for you and generally does what you want.
1.! Take all the grades for this class and calculate final grade for the course 2.! World of Warcraft 3.! Any video game 4.! 401K Lab
Batch
List boxes
! List boxes allow you to select one (or more) items from a list of items ! See this link: http://www.pythonware.com/library/ tkinter/introduction/x5453-patterns.htm ! And the sample code:
!listbox.py
! You can also call showwarning, showerror the only difference will be the icon shown in the window.
More Info
! More information about dialogs of all types is at: ! http://www.pythonware.com/library/ tkinter/introduction/standard-dialogs.htm
References
! http://www.ibm.com/developerworks/ library/l-tkprg/index.html#h4 ! http://epydoc.sourceforge.net/stdlib/ Tkinter.Pack-class.html#pack ! http://effbot.org/tkinterbook ! http://www.pythonware.com/library/ tkinter/introduction/
If you dont get it, try reading these links! Good stuff!