3 - GUIs With Tkinter PDF

Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

Tutorials Applied Visualizaton

GUIs with Tkinter


Summer Term 2010 Why GUI?
Part III - GUIs with Tkinter • Because this is nice
[20:51:11] lyra:~ $ python dosomething.py file1
[20:51:11] lyra:~ $ python dosomething.py file2
[20:51:11] lyra:~ $ python dosomething.py file3
[20:51:11] lyra:~ $ python dosomething.py file4
[20:51:11] lyra:~ $ python dosomething.py file5
[20:51:11] lyra:~ $ python dosomething.py file6
[20:51:11] lyra:~ $ python dosomething.py file7
[20:51:11] lyra:~ $ python dosomething.py file8
[20:51:11] lyra:~ $ python dosomething.py file9
...

1 2

GUIs with Tkinter GUIs with Tkinter


Why GUI? Why GUI?
• But this is nicer • Or the “visualization” way
[20:51:11] lyra:~ $ python doisosurface.py 50
[20:51:11] lyra:~ $
[20:51:11] lyra:~ $
[20:51:11] lyra:~ $
[20:51:11] lyra:~ $
[20:51:11] lyra:~ $
[20:51:11] lyra:~ $
[20:51:11] lyra:~ $
[20:51:11] lyra:~ $
[20:51:11] lyra:~ $ python doisosurface.py 900
[20:51:11] lyra:~ $
[20:51:11] lyra:~ $
[20:51:11] lyra:~ $
[20:51:11] lyra:~ $
[20:51:11] lyra:~ $
[20:51:11] lyra:~ $
[20:51:11] lyra:~ $
[20:51:11] lyra:~ $
[20:51:11] lyra:~ $ python doisosurface.py 1250
[20:51:11] lyra:~ $
[20:51:11] lyra:~ $

3 4
GUIs with Tkinter GUIs with Tkinter
Why GUI? Tkinter
• Or the “visualization” way • Python interface for Tk
• Tk is a library for rapid GUI scripting
• Easy to use
• Good integration in VTK
• Widely available

5 6

GUIs with Tkinter GUIs with Tkinter


Tkinter comes as module for Python Insertion - Python classes
• import Tkinter • The expressions
from Tkinter import * root = Tk()
Tkinter.wantobjects = 0 # WINDOWS users btn = Button(root, text="Quit", command=root.quit)

def say_hi():
print "Hello Class"
• instantiate Python classes
root = Tk()

btn = Button(root, text="Quit", command=root.quit)


• Classes have the usual meaning in Python
btn.pack()
• Definition of objects with attributes and methods
btn2 = Button(root, text="Say Hi", command=say_hi)
btn2.pack() • In order to encapsulate and hide behavior
root.mainloop()

7 8
GUIs with Tkinter GUIs with Tkinter
Insertion - Python classes Tk GUI’s are built hierarchical
• Instantiation uses function syntax • You need one root window
root = Tk() root = Tk()

btn = Button(root, text="Quit", command=root.quit)


• Does not have to be called root, but it usually is
• Attributes and methods are referenced with the • Then you can create other elements as children of that
“.” operator root window (e.g. a Button)
btn.pack() btn = Button(root, text="Quit", command=root.quit)

someotherclass.value = 10

• Syntax is quite similar to that of accessing module


contents

9 10

GUIs with Tkinter GUIs with Tkinter


Tk GUI’s are built hierarchical Tk GUI’s are built hierarchical
Root Window • Of course you can have more than
(Tk()) one hierarchy
Toplevel

Frame Button Root


Window Frame Button

Frame Button
... Button ...
Button

Button ...

11 12
GUIs with Tkinter GUIs with Tkinter
The mainloop() method The event loop in GUI programs
• Last call you issue actively in the entry method
• Starts message processing
• From there, any GUI application is event driven!

• There is usually only one mainloop per thread


(i.e. in our case only one mainloop at all)

• That is why we must differentiate between the Root


window (Tk()) and another Toplevel window
Your script Command Function
(aka Event Handler)

13 14

GUIs with Tkinter GUIs with Tkinter


Widgets Widgets
• Tkinter supports 15 core widgets • Tkinter supports 15 core widgets
• Button • Message
• Canvas • Radiobutton
• Checkbutton • Scale
• Entry • Scrollbar
• Frame • Text
• Label • Toplevel
• Listbox
• Menu
• Menubutton

15 16
GUIs with Tkinter GUIs with Tkinter
Widgets Widgets
• Use all the same configuration interface • You can use a dictionary interface
• Works by keyword arguments >>> w["text"]
'button'
>>> w["text"] = "hello"
w = widgetclass(parent, option=value, ...) >>>

• The cget method lets you get an option value • The “keys()” method works as you would expect
w = Button(root, text="button", command=hello) >>> w.keys()
w.cget('command') ['activebackground', 'activeforeground', 'anchor', 'background', 'bd',
>>> '225192hello' 'bg', 'bitmap', 'borderwidth', 'command', 'compound', 'cursor', 'default',
w.cget('text') 'disabledforeground', 'fg', 'font', 'foreground', 'height',
>>> 'button' 'highlightbackground', 'highlightcolor', 'highlightthickness', 'image',
'justify', 'overrelief', 'padx', 'pady', 'relief', 'repeatdelay',
'repeatinterval', 'state', 'takefocus', 'text', 'textvariable',
'underline', 'width', 'wraplength']
>>>

17 18

GUIs with Tkinter GUIs with Tkinter


Widgets Widgets
• The pack() method • Pack has some useful options
>>> w.pack() >>> w.pack(side=LEFT, fill=BOTH)

• Tells the widget to size itself fit to the given contents • side specifies which side to pack the widget against
and make itself visible • fill specifies if the widget should occupy all the space
• Consequence given to it by its parent
• If you forget to call pack() you won’t see your widget! • expand specifies whether the widget is allowed to
expand in order to fill up empty space

19 20
GUIs with Tkinter GUIs with Tkinter
Commonly used widgets Commonly used widgets
• Button • Canvas
• The probably most widely used control in the world • A surface area you can draw on
• Most important options window = Toplevel(width=800, height=600)
tfCanvas = Canvas(ctrlWindow, width=400, height=250, relief=RAISED,
selectbackground='grey')
• command tfCanvas.pack(anchor=NW, side=TOP)

• The method to call when the button is hit ...

• text tfCanvas.create_line(xs,ys,xe,ye, fill=”black”)

• The text on the button

21 22

GUIs with Tkinter GUIs with Tkinter


Commonly used widgets Commonly used widgets
• Canvas - has many methods • Checkbutton
• create_arc • Represents a variable that can have two distinct values
• create_bitmap • Needs a Tkinter variable to work with
• create_polygon var = IntVar() # this is Tkinters way of saying: I want an int
c = Checkbutton(root, text=”Hello”, variable=var)
• ... c.pack()

• Items can be named, queried and so on • Default is: Button selected, var = 1, 0 otherwise
• Details when we need them • You can query the variable like this
• If you are interested anyway, see the tutorial
value = var.get()

23 24
GUIs with Tkinter GUIs with Tkinter
Commonly used widgets Commonly used widgets
• Checkbutton • Entry
• Has a command option that is called when the state • Represents a single line text entry field
changes root = Tk()

e = Entry(root, width=55)
var = IntVar() # this is Tkinters way of saying: I want an int e.pack()
def say_hello(): def say_hello():
print “Hello”, var.get() print e.get()
c = Checkbutton(root, text=”Hello”, command=say_hello, variable=var)
c.pack() b = Button(root,text="Hello", command=say_hello)
b.pack()

qb = Button(root, text="Quit", command=root.quit)


qb.pack()

root.mainloop()

25 26

GUIs with Tkinter GUIs with Tkinter


Commonly used widgets Commonly used widgets
• Label • Listbox
• Displays text or an image • Displays a list of alternatives
root = Tk() • Very useful for selection purposes
l = Label(root, text="This is rather boring, I suppose") lb = Listbox(root, selectmode=MULTIPLE)
l.pack()
for i in range(10):
qb = Button(root, text="Quit", command=root.quit) lb.insert(END, str(i))
qb.pack()
lb.pack()
root.mainloop()
def say_hello():
print str(lb.curselection())

b = Button(root,text="Hello", command=say_hello)
b.pack()

qb = Button(root, text="Quit", command=root.quit)


qb.pack()

root.mainloop()

27 28
GUIs with Tkinter GUIs with Tkinter
Commonly used widgets Commonly used widgets
• Radiobutton root = Tk()
MODES = [
("Monochrome", "1"),
• Used to select one out of several alternatives ("Grayscale", "L"),
("True color", "RGB"),
• Similar to a checkbutton, but ]
("Color separation", "CMYK"),

• For correct behaviour, all buttons in a group have to v = StringVar()


v.set("L") # initialize
point to the same variable for text, mode in MODES:
v = IntVar() b = Radiobutton(root, text=text, variable=v, value=mode)
Radiobutton(root, text="One", variable=v, value=1).pack(anchor=W) b.pack(anchor=W)
Radiobutton(root, text="Two", variable=v, value=2).pack(anchor=W)
def say_hello():
print v.get()

b = Button(root,text="Hello", command=say_hello)
b.pack()

qb = Button(root, text="Quit", command=root.quit)


qb.pack()

root.mainloop()

29 30

GUIs with Tkinter GUIs with Tkinter


Commonly used widgets Commonly used widgets
• Scale • Text
• The scale widget allows you to set a numerical value by • Used to enter multiline text
drawing a slider root = Tk()

root = Tk() t = Text(root, width=100, height=50)


t.pack()
def dragged(event):
print s.get() def get_value():
v = t.get(1.0,END)
s = Scale(root, orient=HORIZONTAL, from_=10, to_=100, label="Test", command=dragged) print v
s.pack()
b = Button(root, text="Get Value", fg="red", command=get_value)
def get_value(): b.pack()
print s.get()
qb = Button(root, text="Quit", command=root.quit)
b = Button(root, text="Get Value", fg="red", command=get_value) qb.pack()
b.pack()
root.mainloop()
qb = Button(root, text="Quit", command=root.quit)
qb.pack()

root.mainloop()

31 32
GUIs with Tkinter GUIs with Tkinter
Commonly used widgets Commonly used widgets
• Text • Toplevel
• Example 2 • A toplevel finally can be used to create more windows
root = Tk()

t = Text(root, width=100, height=50) root = Tk()


t.pack()
tl = Toplevel()
def execute():
chunk = t.get(1.0,END) t = Text(tl, width=100, height=50)
obj = compile(chunk, '<string>', 'exec') t.pack()
exec obj
def get_value():
b = Button(root, text="Execute", fg="red", command=execute) v = t.get(1.0,END)
b.pack() print v

qb = Button(root, text="Quit", command=root.quit) b = Button(root, text="Get Value", fg="red", command=get_value)


qb.pack() b.pack()

root.mainloop() qb = Button(root, text="Quit", command=root.quit)


qb.pack()

root.mainloop()

33 34

GUIs with Tkinter GUIs with Tkinter


Commonly used widgets Events and Bindings
• Not discussed • Important, since you not only want to react to button
• Frame clicks or selections but also
• Menu • Mouse clicks anywhere
• Menubutton • Mouse movement
• Message • Keyboard input
• Scrollbar
• We won’t need them
• If you are interested, refer to the documentation

35 36
GUIs with Tkinter GUIs with Tkinter
Events and Bindings Events and Bindings
• You bind events to widgets using bind() • Event attributes
widget.bind(event, eventhandler) event.widget # the widget generating the event
event.x # current mouse x position in pixels
event.y # current mouse y position in pixels
• Where event handler has the form event.x_root
event.y_root
# current position relative to upper left screen corner

def eventhandler(event): event.char # the character code (keyboard event)


#do something event.keysym # key symbol (keyboard event)
event.keycode # key code (keyboard event)
event.num # the button number (mouse click events)
event.width # new with of the widget (resize event)
event.height # new height of the widget (resize event)
• Whenever “event” happens on the widget, the event event.type # event type sent

handler gets called and gets passed an event structure

37 38

GUIs with Tkinter GUIs with Tkinter


Events and Bindings Events and Bindings
from Tkinter import * • Event types
root = Tk() • <Button-1>, <Button-2>, ...
def eventtest(event): • Mouse button X pressed
print "Mouse: " , str( (event.x,event.y) )
• <B1-Motion>, <B2-Motion>, ...
tl = Toplevel() • Mouse moved while button X pressed
t = Text(tl, width=100, height=50) • <ButtonRelease-1>, <ButtonRelease-2>, ...
t.pack()
• Mouse button X released
t.bind("<Button-1>", eventtest) • <Double-Button-1>, <Double-Button-2>, ...
def get_value(): • Can you guess that one? :-)
v = t.get(1.0,END)
print v • <Enter>
b = Button(root, text="Get Value", fg="red", command=get_value)
• Mouse pointer entered the widget area
b.pack() • <Leave>
qb = Button(root, text="Quit", command=root.quit) • Mouse pointer left the widget area
qb.pack()

root.mainloop()

39 40
GUIs with Tkinter GUIs with Tkinter
Events and Bindings Events and Bindings
• Event types • Bindings
• <Return> • The bind() method creates an instance binding
• User pressed the return key
• Can use BackSpace, Tab, Shift_L, Shift_R, Control_L, Alt_L, and so on
• Event handlers are executed on a specific widget instance
• <Key> • You can also bind at toplevel, class or application level
• User pressed any key (query via event.char)
• a, b, c, ...
• Toplevel uses bind() on toplevel window
• User pressed a, b, c ... most printable characters can be used as is • On a class of widgets use bind_class()
• <Shift-Up> • But, don’t do that, really...
• User pressed Shift and the UP arrow
• For application level use bind_all() on the root window
• Most key events can be prefixed by Alt, Shift and Control

41 42

GUIs with Tkinter GUIs with Tkinter


Events and Bindings Comprehensive tutorial and reference
• Bindings
root = Tk()

def eventtest(event):
print "Mouse: " , str( (event.x,event.y) )

tl = Toplevel() http://www.pythonware.com/library/tkinter/
t = Text(tl, width=100, height=50)
t.pack()
introduction/index.htm
root.bind_all("<Enter>", eventtest)

def get_value():
v = t.get(1.0,END)
print v

b = Button(root, text="Get Value", fg="red", command=get_value)


b.pack()

qb = Button(root, text="Quit", command=root.quit)


qb.pack()

root.mainloop()

43 44

You might also like