Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

GUI Programming in Python Using Tkinter

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 47

GUI Programming in Python

using Tkinter

-by Mrs. J. Vijayalakshmi


Sri Sai Ram Engineering College
GUIs for Python
-Tkinter (standard GUI library for Python)
-wxPython
-JPython
Requirement

Import the Tkinter module.


Create the GUI application main window.
Add one or more of the widgets to the GUI
application.
Enter the main event loop to take action
against each event triggered by the user.
Requirement
1. Import the Tkinter module (or from Tkinter import *).
2. Create a top-level windowing object that contains your
entire GUI application.
3. Build all your GUI components (and functionality) on
top (or within) of your top-level windowing object.
4. Connect these GUI components to the underlying
application code.
5. Enter the main event loop.- This loop runs forever
waiting for GUI events, processing them, and then going
to wait for more events to process.
Example
#!/usr/bin/python
import tkinter
top = tkinter.Tk()
# Code to add widgets will go here...
top.mainloop()
Tkinter Widgets
1. Button
2. Canvas
3. Checkboxes
4. Entry(to display a single-line text field for accepting values from a user.)
5. Frame
6. Label
7. Listbox
8. Menubotton
9. Menu
10. Message(to display multiline text fields for displaying values from a user.)
11. Radiobutton
12. Scale
13. Scrollbar
14. Text (to accept text in multiple lines.)
Tkinter Widgets
15. Toplevel
16. Spinbox
17. PanedWindow
18. LabelFrame
19.tkMessageBox
Standard Attributes
1. Dimensions (Various lengths, widths, and other dimensions of widgets can be described in many
different units c-centimeters, i inches, m-millimeters,)Length options borderwidth, height,width)
2. Colors- Two ways to specify
a. RGB in hexadecimal value ( #fff white, #000000 black , #000fff000- green
b. Use standard color name - "white", "black", "red", "green", "blue", "cyan", "yellow",
1. Fonts- 2 ways to specify the type style 1. Simple Tuple Fonts ex ("Helvetica", "16"), ("Times", "24", "bold
italic")2. Font object Fonts
import tkFont font = tkFont.Font ( option, ... )
family The font family name as a string.
size The font height as an integer in points. To get a font n pixels high, use -n.
weight "bold" for boldface, "normal" for regular weight.
slant "italic" for italic, "roman" for unslanted.
underline 1 for underlined text, 0 for normal.
overstrike 1 for overstruck text, 0 for normal.
Ex. helv36 = tkFont.Font(family="Helvetica",size=36,weight="bold")

4. Cursors (arrow,"circle,"clock,"cross)
Ex: from Tkinter import *
import Tkinter top = Tkinter.Tk()
B1 = Tkinter.Button(top, text ="circle", relief=RAISED,\ cursor="circle")
B2 = Tkinter.Button(top, text ="plus", relief=RAISED,\ cursor="plus")
B1.pack()
B2.pack()
top.mainloop()
Geometry Management
1. Geometry Manager Classes:
a. The pack() Method This geometry manager
organizes widgets in blocks before placing them
in the parent widget.
b. The grid() Method This geometry manager
organizes widgets in a table-like structure in the
parent widget.
c. The place() Method This geometry manager
organizes widgets by placing them in a specific
position in the parent widget.
Geometry Management PACK()
widget.pack( pack_options )
-expand When set to true, widget expands to
fill any space not otherwise used in widget's
parent.
fill Determines whether widget fills any extra
space allocated to it by the packer, or keeps its
own minimal dimensions: NONE (default), X (fill
only horizontally), Y (fill only vertically), or BOTH
(fill both horizontally and vertically).
side Determines which side of the parent
widget packs against: TOP (default), BOTTOM,
LEFT, or RIGHT.
Geometry Management PACK()
from tkinter 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()
Geometry Management PACK()
Placing a number of widgets on top of each other
To put a number of widgets in a column, you can use
the pack method without any options:
from tkinter import *
root = Tk()
w = Label(root, text="Red", bg="red,fg="white")
w.pack()
w=Label(root, text="Green", bg="green", fg="black")
w.pack()
w = Label(root, text="Blue", bg="blue", fg="white")
w.pack()
mainloop()
Geometry Management PACK()
You can use the fill=X option to make all widgets as
wide as the parent widget:
from tkinter import *
root = Tk()
w = Label(root, text="Red", bg="red", fg="white")
w.pack(fill=X)
w= Label(root, text="Green", bg="green", fg="black")
w.pack(fill=X)
w = Label(root, text="Blue", bg="blue", fg="white")
w.pack(fill=X)
mainloop()
Geometry Management PACK()
Placing a number of widgets side by side
To pack widgets side by side, use the side option. If you
wish to make the widgets as high as the parent, use the
fill=Y option too:
from tkinter import *
root = Tk()
w = Label(root, text="Red", bg="red", fg="white")
w.pack(side=LEFT)
w = Label(root, text="Green", bg="green", fg="black")
w.pack(side=LEFT)
w = Label(root, text="Blue", bg="blue", fg="white")
w.pack(side=LEFT)
mainloop()
Event Driven
Usually, widgets have some associated
behaviors, such as when a button is pressed, or
text is filled into a text field. These types of user
behaviors are called events, and the GUIs
response to such events are known as callbacks.
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
Event Handling
Event sources (widgets) can specify their handlers
command handlers - use the 'command=' keyword
followed by the command you want executed
callbacks
A callback is the name of the function that is to be run in
response of an event
Callbacks can be defined as a free standing function in our
program or as a class member
Ex1.
from tkinter import *
root = Tk()
Button (root, text='Press Me', command=root.quit).pack(side=LEFT)
root.mainloop()
Event Handling
from tkinter import *
def quit():
print 'Hello, getting out of here'
import sys; sys.exit()
widget = Button(None, text='Press me to quit' ,
command=quit)
widget.pack()
widget.mainloop()
Bound Method Callbacks
from tkinter import *
class HelloClass:
# create the window in the class constructor
def __init__(self):
widget = Button(None, text='Press Me to quit',
command=self.quit)
widget.pack()
def quit(self):
print ('leaving now)
import sys ; sys.exit()
HelloClass() # create a HelloClass object
mainloop()
Binding Event
from tkinter import *
def hello(event):
print 'Double click to exit'
def quit(event):
print 'caught a double click, leaving'
import sys ; sys.exit()
widget = Button(None, text='Hello Event World')
widget.pack()
widget.bind(<Button-1>', hello)
widget.bind(<Double-1>' , quit)
widget.mainloop()
Tkinter Widgets
Tkinter Widgets
1. Button: Button(master=None, **options).
2. Label(master=None, **options)
Program that toggle the button background color
import Tkinter as tk button1 = tk.Button(frame1, compound=tk.TOP, width=148,
button_flag = True height=240, image=photo1,
def click(): text="optional text", bg='green', command=click)
"""
.respond to the button click button1.pack(side=tk.LEFT, padx=2, pady=2)
# save the button's image from garbage collection (needed?)
""" button1.image = photo1
global button_flag # start the event loop
# toggle button colors as a test root.mainloop()
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
Widget Configuration
Configuration can be specified at creation time or changed as the program is running by using
the config method

import Tkinter
top = Tkinter.Tk()
w = Tkinter.Label(top, text="Hello, world!")
w.pack()
w.config(text="Hello Jim!")
Tkinter.mainloop()
Updating the text variable
from Tkinter import *
root = Tk()
# To create a Tkinter variable, call the corresponding constructor
v = StringVar()
label = Label(root, textvariable = v).pack()
v.set("New Text!")
print v.get()
root.mainloop()
Label and Button Demo

import tkinter
top = tkinter.Tk()
hello = tkinter.Label(top, text='Hello World!')
hello.pack()
quit = tkinter.Button(top, text='QUIT', command=top.quit,
bg='red', fg='white')
quit.pack(fill=Tkinter.X, expand=1)
tkinter.mainloop()
Pack Geometry Manager
from tkinter import *
root = Tk()
w = Label(root, text="Red", bg="red", fg="white")
w.pack()
w = Label(root, text="Green", bg="green", fg="black")
w.pack()
w = Label(root, text="Blue", bg="blue", fg="white")
w.pack()
mainloop()

from Tkinter 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()
Grid Geometry Manager
Button(win, font=('courier',10), text='C,width=4,height=2, command=lambda: click('C')).grid(row=0,column=5)
Button(win, font=('courier',10), text='7',width=4,height=2, command=lambda: click('7')).grid(row=1,column=1)
Button(win, font=('courier',10), text='8',width=4,height=2, command=lambda: click('8')).grid(row=1,column=2)
Button(win, font=('courier',10), text='9',width=4,height=2, command=lambda: click('9')).grid(row=1,column=3)
Button(win, font=('courier',10), text='4',width=4,height=2, command=lambda: click('4')).grid(row=2,column=1)
Button(win, font=('courier',10), text='5',width=4,height=2, command=lambda: click('5')).grid(row=2,column=2)
Button(win, font=('courier',10), text='6',width=4,height=2, command=lambda: click('6')).grid(row=2,column=3)
Button(win, font=('courier',10), text='1',width=4,height=2, command=lambda: click('1')).grid(row=3,column=1)
Button(win, font=('courier',10), text='2',width=4,height=2, command=lambda: click('2')).grid(row=3,column=2)
Button(win, font=('courier',10), text='3',width=4,height=2, command=lambda: click('3')).grid(row=3,column=3)
Button(win, font=('courier',10), text='0',width=4,height=2, command=lambda: click('0')).grid(row=4,column=1)
Button(win, font=('courier',10), text='+/',width=4,height=2, command=lambda: click('+/')).grid(row=4,column=2)
Button(win, font=('courier',10), text='.',width=4,height=2, command=lambda: click('.')).grid(row=4,column=3)
Message widget
The Message widget is used to display text. This is a widget not a
text window. Use for on screen instructions or to make a custom
message window
from tkinter import *
master =Tk()
msg = Message(master, text=' The best way
to predict the future is to invent it. Alan
options: background/bg
Kay') borderwidth/bd
cursor ,text, font
msg.config(font=('times',14)) textvariable
foreground/fg
msg.pack() Width, Highlight
background
mainloop() highlightcolor
highlightthickness
justify
Message widget
The Message widget is used to display text. This is a widget not a
text window. Use for on screen instructions or to make a custom
message window
from tkinter import *
master =Tk()
msg = Message(master, text=' The best way
to predict the future is to invent it. Alan
options: background/bg
Kay') borderwidth/bd
cursor ,text, font
msg.config(font=('times',14)) textvariable
foreground/fg
msg.pack() Width, Highlight
background
mainloop() highlightcolor
highlightthickness
justify
Entry widget options:
background/bg
borderwidth/bd
used to enter or display a single line of text takefocus
To enter multiple lines of text, use the Text widget. Cursor
Ex: text ,font
textvariable
from tkinter import * foreground/fg
width
master = Tk() highlightbackground
validate
e = Entry(master) highlightcolor
validatecommand
e.pack() methods:
get()
set()
mainloop() delete(first,last/END)
insert(index)
insert(index,string)
icursor(index)
index(index)
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
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
Frame Example
from Tkinter 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()
Checkbuttons and Radiobuttons
Checkbuttons are used for multiple choice situations, i.e. choosing m of n possible
options. This is done by assigning each checkbox a variable of its own.
Radiobuttions are used for choosing one of n possible choices; i.e. a mutually exclusive
single choice by giving each button a unique value of the same Tkinter variable
Ex:
from Tkinter import *
def cb():
print "variable is", var.get()
win = Tk()
var = IntVar()
c = Checkbutton(
win, text="Enable Tab",
variable=var,
command= (cb)
c.pack()
mainloop()
Checkbuttons and Radiobuttons
Ex3. c2 = Checkbutton( f, text="Wine,
from Tkinter import * variable=var2, command= cb)
def cb(): c2.pack(side=TOP)
print "beer is", var1.get()
c3 = Checkbutton( f, text="Water",
print "Wine is", var2.get()
variable=var3, command= cb)
print "Water is", var3.get()
win = Tk() c3.pack(side=TOP)
f = Frame(relief=RAISED , f.pack()
borderwidth=5) mainloop()
var1 = IntVar()
var2 = IntVar()
var3 = IntVar()
c1 = Checkbutton(
f, text="Beer",
variable=var1,
command= cb)
c1.pack(side=TOP)
Radiobuttons demo
from tkinter import *
def change():
print ('Station = ' , var.get())
root = Tk()
stations = 'WAAL' , 'WSKG' , 'WSQX' , 'WNBF'
f = Frame(relief=RAISED , borderwidth=5)
var = StringVar()
for station in stations:
radio = Radiobutton(f, text=station, variable=var ,value=station)
radio.pack(side=TOP)
f.pack()
Button(root,text='New' , command= change).pack()
var.set('WAAL') #initalize the set of radio buttons
mainloop()
Radiobuttons demo
from tkinter import *
def change():
print ('Station = ' , var.get())
root = Tk()
stations = 'WAAL' , 'WSKG' , 'WSQX' , 'WNBF'
f = Frame(relief=RAISED , borderwidth=5)
var = StringVar()
for station in stations:
radio = Radiobutton(f, text=station, variable=var ,value=station)
radio.pack(side=TOP)
f.pack()
Button(root,text='New' , command= change).pack()
var.set('WAAL') #initalize the set of radio buttons
mainloop()
Radiobuttons demo
from tkinter import *
def sel():
selection = "You selected the option " + str(var.get())
label.config(text = selection)
root = Tk()
var = IntVar()
R1 = Radiobutton(root, text="Option 1", variable=var, value=1, command=sel)
R1.pack( anchor = W )
R2 = Radiobutton(root, text="Option 2", variable=var, value=2, command=sel)
R2.pack( anchor = W )
R3 = Radiobutton(root, text="Option 3", variable=var, value=3, command=sel)
R3.pack( anchor = W)
label = Label(root)
label.pack()
root.mainloop()
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.
Sliders & Scale demo
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()
def onMove(self, value):
print 'onMove = ' , value
def readScale(self):
print 'readscale = ' , self.var.get()
#if __name__ == '__main__' :
SliderDemo().mainloop()
List Box
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
Ex:
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()
Scrollbox
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.
Scrollbox
from tkinter import *
master = Tk()
scrollbar = Scrollbar(master)
scrollbar.pack(side=RIGHT, fill=Y)
listbox = Listbox(master, yscrollcommand=scrollbar.set)
for i in range(1000):
listbox.insert(END, str(i))
listbox.pack(side=LEFT, fill=BOTH)
scrollbar.config(command=listbox.yview)
mainloop()
Get selected value from Listbox
import Tkinter F2 = Tkinter.Frame()
F1 = Tkinter.Frame() lab = Tkinter.Label(F2)
s = Tkinter.Scrollbar(F1) def poll():
L = Tkinter.Listbox(F1) lab.after(200, poll)
s.pack(side=Tkinter.RIGHT, sel = L.curselection()
fill=Tkinter.Y)
L.pack(side=Tkinter.LEFT, lab.config(text=str(sel))
fill=Tkinter.Y) lab.pack()
s['command'] = L.yview F2.pack(side=Tkinter.TOP)
L['yscrollcommand'] = s.set poll()
for i in range(30): Tkinter.mainloop()
L.insert(Tkinter.END, str(i))
F1.pack(side=Tkinter.TOP)
Adding Two Numbers in Grid Layout
from tkinter import *

def add():
m1.config(text=str(int(firstno.get())+int(secondno.get())))
top=Tk()
top.title("Adding two Numbers")
l1=Label(top,text="Enter the First No")
l1.grid(row=0,column=0)
firstno=Entry(top)
firstno.grid(row=0,column=1)

l2=Label(top,text="Enter the Second Number")


l2.grid(row=1,column=0)
secondno=Entry(top)
secondno.grid(row=1,column=1)

b1=Button(top, text="ADD", command=add)


b1.grid(row=2,column=0)

m1=Message(top)
m1.grid(row=2,column=1)
top.mainloop()
Adding Menu Example
from tkinter import *
import sys
def doNothing():
print("Test")
root = Tk()
root.title("TextEditor")
root.geometry("300x200")
menu = Menu(root)
root.config(menu=menu)
subMenu = Menu(menu)
menu.add_cascade(label="File", menu=subMenu)
subMenu.add_command(label="New Project...", command =doNothing)
subMenu.add_command(label="Save", command=doNothing)
subMenu.add_separator()
editMenu = Menu(menu)
menu.add_cascade(label="Edit", menu=editMenu)
editMenu.add_command(label="Undo",command=doNothing)
root.mainloop()

You might also like