GUI Programming Using Tkinter PDF
GUI Programming Using Tkinter PDF
GUI PROGRAMMING
USING TKINTER
Cuauhtmoc Carbajal
ITESM CEM
April 17, 2013
2
Agenda
Introduction
Tkinter and Python Programming
Tkinter Examples
3
INTRODUCTION
4
Introduction
In this lecture, we will give you a brief introduction to the
subject of graphical user interface (GUI) programming.
We cannot show you everything about GUI application
development in just one lecture, but we will give you a very
solid introduction to it.
The primary GUI toolkit we will be using is Tk, Pythons default
GUI. Well access Tk from its Python interface called Tkinter
(short for Tk interface).
Tk is not the latest and greatest, nor does it have the most
robust set of GUI building blocks, but it is fairly simple to use,
and with it, you can build GUIs that run on most platforms.
Once you have completed this lecture, you will have the skills
to build more complex applications and/or move to a more
advanced toolkit. Python has bindings or adapters to most of
the current major toolkits, including commercial systems.
5
Event-Driven Processing
Events can include the actual button press (and release),
mouse movement, hitting the Return or Enter key, etc. The
entire system of events that occurs from the beginning until the
end of a GUI application is what drives it. This is known as
event-driven processing.
One example of an event with a callback is a simple mouse
move. Suppose that the mouse pointer is sitting somewhere on
top of your GUI application. If you move the mouse to another
part of your application, something has to cause the movement
of the mouse to be replicated by the cursor on your screen so
that it looks as if it is moving according to the motion of your
hand. These are mouse move events that the system must
process portray your cursor moving across the window. When
you release the mouse, there are no more events to process,
so everything just remains idle on the screen again.
13
Geometry Managers
Geometrymanagersallowustoorganizewidgetsinsideofacontainer
Placegeometrymanager
http://effbot.org/tkinterbook/place.htm
Packgeometrymanager
http://effbot.org/tkinterbook/pack.htm
Gridgeometrymanager
http://effbot.org/tkinterbook/grid.htm
15
Geometry Managers
Tk has three geometry managers that help with
positioning your widgetset:
Placer: You provide the size of the widgets and locations to place
them; the manager then places them for you. The problem is that
you have to do this with all the widgets, burdening the developer
with coding that should otherwise take place automatically.
Packer: it packs widgets into the correct places (namely the
containing parent widgets, based on your instruction), and for every
succeeding widget, it looks for any remaining real estate into
which to pack the next one. The process is similar to how you
would pack elements into a suitcase when traveling.
Grid: It is used to specify GUI widget placement, based on grid
coordinates. The Grid will render each object in the GUI in their grid
position.
We will stick with the Packer.
16
Packer
Once the Packer has determined the sizes and alignments of
all your widgets, it will then place them on the screen for you.
When all the widgets are in place, we instruct the application to
enter the aforementioned infinite main loop. In Tkinter, the code
that does this is:
Tkinter.mainloop()
This is normally the last piece of sequential code your program
runs.
When the main loop is entered, the GUI takes over execution
from there.
All other actions are handled via callbacks, even exiting your
application. When you select the File menu and then click the
Exit menu option or close the window directly, a callback must
be invoked to end your GUI application.
17
1. LoadawidgetclassfromTkinter
2. Makeaninstanceofit
(repeat1and2asneeded)
3. Arrangethewidgetinitsparentwidget
4. Entertheeventloop
python3
from tkinter import Label
python
from Tkinter import Label
19
http://effbot.org/tkinterbook/tkintereventsandbindings.htm
20
Event Handling
Event sources (widgets) can specify their handlers
command handlers
callbacks
21
Command Handlers
usethe'command='keywordfollowedbythecommandyouwantexecuted
ex:
fromTkinter import*
root=Tk()
Button(root,text='PressMe',command=root.quit).pack(side=LEFT)
root.mainloop()
22
Callbacks
Acallbackisthenameofthefunctionthatistoberuninresponseof
anevent
Callbackscanbedefinedasafreestandingfunction inourprogramor
asaclass member.
ex.
fromTkinter import*
def quit():
print'Hello,gettingoutofhere'
importsys;sys.exit()
widget=Button(None,text='Pressmetoquit',command=quit)
widget.pack()
widget.mainloop()
23
HelloClass()#createaHelloClass object
mainloop()
24
Binding Events
fromTkinter import*
def hello(event):
print 'Doubleclicktoexit'
def quit(event):
print 'caughtadoubleclick,leaving'
importsys;sys.exit()
widget=Button(None,text='HelloEventWorld')
widget.pack()
widget.bind('<Button1>',hello)
widget.bind('<Double1>' ,quit)
widget.mainloop()
25
TKINTER WIDGETS
26
Tk Widgets
Widget Description
Button Similar to a Label but provides additional functionality for mouse-overs, presses, and releases,
as well as keyboard activity/events
Canvas Provides ability to draw shapes (lines, ovals, polygons, rectangles); can contain images or
bitmaps
Checkbutton Set of boxes, of which any number can be checked
Entry Single-line text field with which to collect keyboard input
Frame Pure container for other widgets
Label Used to contain text or images
LabelFrame Combo of a label and a frame but with extra label attributes
Listbox Presents the user with a list of choices from which to choose
Menu Actual list of choices hanging from a Menubutton from which the user can choose
Menubutton Provides infrastructure to contain menus (pulldown, cascading, etc.)
Message Similar to a Label, but displays multiline text
PanedWindow A container widget with which you can control other widgets placed within it
Radiobutton Set of buttons, of which only one can be pressed
Scale Linear slider widget providing an exact value at current setting; with defined starting and
ending values
Scrollbar Provides scrolling functionality to supporting widgets, for example, Text, Canvas, Listbox, and
Entry
Spinbox Combination of an entry with a button letting you adjust its value
Text Multiline text field with which to collect (or display) text from user
Toplevel Similar to a Frame, but provides a separate window container
27
Standard attributes
Dimensions
Colors
Fonts
Anchors
used to define where text is positioned
relative to a reference point.
Relief styles
refers to certain simulated 3-D effects
around the outside of the widget.
Bitmaps
used to display a bitmap type: "error,
"gray75, "gray50. "gray25, "gray12,
"hourglass, "info, "questhead, "question,
"warning"
Cursors
28
Button
Button(master=None, **options) (class) [#] A command button.
master Parent widget. **options Widget options. See the description of
the config method for a list of available options.
Buttons can contain text or images, and you can
associate a Python function or method with each button.
When the button is pressed, Tkinter automatically calls
that function or method.
The button can only display text in a single font, but the
text may span more than one line. In addition, one of the
characters can be underlined, for example to mark a
keyboard shortcut. By default, the Tab key can be used to
move to a button widget.
29
top = Tkinter.Tk()
quit = Tkinter.Button(top, text='Hello World!',
command=top.quit)
quit.pack()
Tkinter.mainloop()
tkhello2.py
30
import Tkinter as tk
button_flag = True
def click():
"""
respond to the button click
"""
global button_flag
# toggle button colors as a test
if button_flag:
button1.config(bg="white")
button_flag = False
else:
button1.config(bg="green")
button_flag = True
root = tk.Tk()
# create a frame and pack it
frame1 = tk.Frame(root)
frame1.pack(side=tk.TOP, fill=tk.X)
# pick a (small) image file you have in the working directory ...
photo1 = tk.PhotoImage(file="rpi.gif")
# create the image button, image is above (top) the optional text
button1 = tk.Button(frame1, compound=tk.TOP, width=148, height=240, image=photo1,
text="optional text", bg='green', command=click)
"padx" puts a bit of extra space to
button1.pack(side=tk.LEFT, padx=2, pady=2) the left and right of the widget, while
# save the button's image from garbage collection (needed?) "pady" adds extra space top and
button1.image = photo1 bottom.
# start the event loop
root.mainloop()
button-image.py
31
Label
Label(master=None, **options) (class) [#] Display a single line of text, or an
image.
master Parent widget. **options Widget options. See the description of the
config method for a list of available options.
top = Tkinter.Tk()
label = Tkinter.Label(top, text='Hello World!')
label.pack()
Tkinter.mainloop()
tkhello1.py
33
Widget Configuration
Configuration can be specified at creation time or changed as the
program is running by using the config method
ex.
import Tkinter
top = Tkinter.Tk()
w = Tkinter.Label(top, text="Hello, world!")
w.pack()
w.config(text="Hello Jim!")
Tkinter.mainloop()
34
root = Tk()
print v.get()
root.mainloop()
35
Tkinter.mainloop()
tkhello3.py
36
fromTkinter import*
root=Tk()
w=Label(root,text="Red",bg="red",fg="white").pack(side=LEFT)
w=Label(root,text="Green",bg="green",fg="black").pack(side=LEFT)
w=Label(root,text="Blue",bg="blue",fg="white").pack(side=LEFT)
mainloop()
37
def helloCallBack():
tkMessageBox.showinfo("HelloPython","HelloWorld")
B=Tkinter.Button(top,text="Hello",command=helloCallBack)
B.pack()
B.place(bordermode=OUTSIDE,height=100,width=100)
top.mainloop()
39
MORE WIDGETS
ENTRY , CHECKBUTTONS, RADIO BUTTONS, SCALE
40
Message
TheMessagewidgetisusedtodisplaytext.Thisisawidgetnotatext
window.Useforonscreeninstructionsortomakeacustommessagewindow
from Tkinter import*
master=Tk()
msg =Message(master,text='Thebestwaytopredictthefutureistoinventit.Alan
Kay')
msg.config(font=('times',14)) options:
msg.pack() anchor padx
mainloop() aspect pady
background/bg relief
borderwidth/bd takefocus
cursor text
font textvariable
foreground/fg width
highlightbackground
highlightcolor
highlightthickness
justify
41
Entry
used to enter or display a single line of text
To enter multiple lines of text, use the Text widget.
from Tkinter import *
master = Tk()
e = Entry(master)
e.pack()
mainloop()
methods:
options: get()
anchor set()
aspect delete(first,last/END)
background/bg relief insert(index)
borderwidth/bd takefocus insert(index,string)
cursor text icursor(index)
font textvariable index(index)
foreground/fg width
highlightbackground validate
highlightcolor validatecommand
highlightthickness justify
42
Entry
from Tkinter import *
master = Tk()
e = Entry(master)
e.pack()
def callback():
print e.get()
Frame Widget
Frames are used as containers for other widgets. Widgets placed in a
frame can use any of the geometry managers (but only one per
frame)
You can have multiple frames per window
Options:
bg background color
bd border width (default=2 pixels)
cursor cursor to use when hovering over the frame
height vertical dimension of the frame
highlightbackground color when frame doesnt have focus
highlightcolor color when frame has focus
highlightthickness thickness of the focus highlight
relief FLAT, Raised, Sunken, GROOVE, RIDGE;
default = FLAT
width width of the frame
44
Frame Example
fromTkinter import*
root=Tk()
frame=Frame(root)
frame.pack()
bottomframe =Frame(root)
bottomframe.pack(side=BOTTOM)
redbutton =Button(frame,text="Red",fg="red")
redbutton.pack(side=LEFT)
greenbutton =Button(frame,text="Brown",fg="brown")
greenbutton.pack(side=LEFT)
bluebutton =Button(frame,text="Blue",fg="blue")
bluebutton.pack(side=LEFT)
blackbutton =Button(bottomframe,text="Black",fg="black")
blackbutton.pack(side=BOTTOM)
root.mainloop()
45
Checkbutton
fromTkinter import*
def cb():
print"variableis",var.get()
win=Tk()
var =IntVar()
c=Checkbutton(
win,text="EnableTab",
variable=var,
command=(lambda:cb()))
c.pack()
mainloop()
checkbutton.py
47
Checkbutton (2)
fromTkinter import * c2=Checkbutton(
f,text="Wine",
def cb(): variable=var2,
print "beeris",var1.get() command=(lambda:cb()))
print "Wineis",var2.get() c2.pack(side=TOP)
print "Wateris",var3.get()
c3=Checkbutton(
win=Tk() f,text="Water",
f=Frame(relief=RAISED,borderwidth=5) variable=var3,
var1=IntVar() command=(lambda:cb()))
var2=IntVar() c3.pack(side=TOP)
var3=IntVar() f.pack()
checkbutton2.py
c1=Checkbutton( mainloop()
f,text="Beer",
variable=var1,
command=(lambda:cb()))
c1.pack(side=TOP)
48
Radiobuttons
from Tkinter import *
def change():
print 'Station = ' , var.get()
root = Tk()
f = Frame(relief=RAISED , borderwidth=5)
var = StringVar()
f.pack(pady=10)
Button(root,text='New' , command=(lambda: change())).pack(pady=10)
var.set('WAAL') #initalize the set of radio buttons
mainloop()
49
Radiobutton (2)
from Tkinter import *
def sel():
selection = "You selected the option " + str(var.get())
label.config(text = selection)
root = Tk()
var = IntVar()
label = Label(root)
label.pack()
root.mainloop()
radiobutton2.py
50
Sliders
A slider is a Tkinter object with which a user can set a
value by moving an indicator. Sliders can be vertically or
horizontally arranged. A slider is created with the Scale
method().
Using the Scale widget creates a graphical object, which
allows the user to select a numerical value by moving a
knob along a scale of a range of values. The minimum
and maximum values can be set as parameters, as well
as the resolution. We can also determine if we want the
slider vertically or horizontally positioned. A Scale widget
is a good alternative to an Entry widget, if the user is
supposed to put in a number from a finite range, i.e. a
bounded numerical value.
51
master = Tk()
w = Scale(master, from_=0, to=42)
w.pack()
w = Scale(master, from_=0, to=200, orient=HORIZONTAL)
w.pack()
mainloop()
52
Scale/Sliders
from Tkinter import *
class SliderDemo(Frame):
def __init__(self,parent=None):
Frame.__init__(self,parent)
self.pack()
self.var = IntVar()
Scale(self,label='Miles',
command=self.onMove,
variable = self.var,
from_=0 , to=100 ,length=200,
tickinterval=20).pack()
Button(self , text='Read', command=self.readScale).pack(pady=10)
def readScale(self):
print 'readscale = ' , self.var.get()
if __name__ == '__main__' :
SliderDemo().mainloop()
53
tkhello4.py
54
Listbox
The Listbox widget is used to display a list of alternatives. The
listbox can only contain text items, and all items must have the
same font and color. Depending on the widget configuration,
the user can choose one or more alternatives from the list.
When to use the Listbox Widget
Listboxes are used to select from a group of textual items. Depending
on how the listbox is configured, the user can select one or many
items from that list.
Patterns
When you first create the listbox, it is empty. The first thing to do is
usually to insert one or more lines of text. The insert method takes an
index and a string to insert. The index is usually an item number (0 for
the first item in the list), but you can also use some special indexes,
including ACTIVE, which refers to the active item (set when you click
on an item, or by the arrow keys), and END, which is used to append
items to the list.
55
Listbox example
from Tkinter import *
master = Tk()
listbox = Listbox(master)
listbox.pack()
listbox.insert(END, "a list entry")
for item in ["one", "two", "three", "four"]:
listbox.insert(END, item)
mainloop()
56
Scrollbar
This widget is used to implement scrolled listboxes,
canvases, and text fields.
Patterns
The Scrollbar widget is almost always used in conjunction with a
Listbox, Canvas, or Text widget. Horizontal scrollbars can also be
used with the Entry widget.
To connect a vertical scrollbar to such a widget, you have to do two
things:
Set the widgets yscrollcommand callbacks to the set method of the
scrollbar.
Set the scrollbars command to the yview method of the widget.
57
Scrollbar Example
from Tkinter import *
master = Tk()
scrollbar = Scrollbar(master)
scrollbar.pack(side=RIGHT, fill=Y)
scrollbar.config(command=listbox.yview)
mainloop()
58
F1.pack(side=Tkinter.TOP)
59
class ScrolledList(Frame):
def __init__(self,options,parent=None):
Frame.__init__(self,parent)
self.pack(expand=YES , fill=BOTH)
self.makeWidgets(options)
def handleList(self,event):
index = self.list.curselection()
label = self.list.get(index)
self.runCommand(label)
Canvas
The Canvas is a rectangular area intended for drawing
pictures or other complex layouts. You can place
graphics, text, widgets, or frames on a Canvas.
Syntax:
w = Canvas ( master, option=value, ... )
Parameters:
master: This represents the parent window.
options: Here is the list of most commonly used options for this
widget. These options can be used as key-value pairs separated by
commas.
61
Canvas (2)
The Canvas widget can support the following standard items:
arc . Creates an arc item.
coord = 10, 50, 240, 210
arc = canvas.create_arc(coord, start=0, extent=150,
fill="blue")
image . Creates an image item, which can be an instance of either the
BitmapImage or the PhotoImage classes.
filename = PhotoImage(file = "sunshine.gif")
image = canvas.create_image(50, 50, anchor=NE,
image=filename)
line . Creates a line item.
line = canvas.create_line(x0, y0, x1, y1, ..., xn, yn,
options)
oval . Creates a circle or an ellipse at the given coordinates.
oval = canvas.create_oval(x0, y0, x1, y1, options)
polygon . Creates a polygon item that must have at least three
vertices.
oval = canvas.create_polygon(x0, y0, x1, y1,...xn, yn,
options)
62
Canvas (3)
import Tkinter
import tkMessageBox
top = Tkinter.Tk()
C = Tkinter.Canvas(top, bg="blue", height=250, width=300)
coord = 10, 50, 240, 210
arc = C.create_arc(coord, start=0, extent=150, fill="red")
C.pack()
top.mainloop()