Unit 14
Unit 14
14.1 Introduction
14.2 Objectives
14.3 Terminologies
14.4 Graphical User interface (GUI)
14.5 Different types of packages for GUI development in Python
14.6 Tkinter (GUI toolkit that comes with Python)
Video 14: Creating GUI for Python with Tkinter
14.7 GUI with wxPython
Video 15: Python GUI with WxFrame
14.8 Summary
14.9 Referance
14.10 Answer to check your progress
14.1 INTRODUCTION
In this unit you will learn components of GUI and Tkinter standard GUI
library that is bundled with python and wxPython libraries. You will also
learn different types of packages available for GUI development. There are
eight (8) examples to study Tkinter standard library and three (3) examples to
study wxPython.
Line numbers before the programming code are included for easy references.
But do not to include line numbers when you code in the text editor. Essential
lines in the code are described after the program code.
14.2 OBJECTIVES
Upon completion of this unit you will be able to:
• Describe Graphical User Interface (GUI) and its components.
• Idetify different types of packages for python GUI implement.
• Demonstrate the skills of programming in Tkinter GUI standard library.
• Demonstrate GUI programming with wxPython cross platform libraries.
• Aply event driven programming for GUI using Tkinter and wxPython
libraries
35
Data Handling, Mobile
Application & Gui
Development Using
14.3 TERMINOLOGIES
Python
GUI: Graphical User Iterface
widget: building blocks that make up an application in a GUI
36
e
widget - the general word for visual building blocks to interact an Activityin Python
Graphical User
GUI. Interface
Development
Layouts -The way you arrange the widgets in a GUI.
Parent, child – A relationship of parent and child is created for any crated
widget. For example, when a check button placed on a frame, frame becomes
parent and check button becomes child.
37
Data Handling, Mobile
Application & Gui
Example 14.1 Tkinter GUI window
Development Using
Python 1 #/user/bin/python
2 import Tkinter as tk1
3 tp=tk1.Tk()
4 # Codes for widgets
5 tp.mainloop()
1 Self executing script, in linux you can run by ‘ ./’ rather than
typing python <file name>.py
2 Import Tkinter library
3 Tkinter Tk window is assigned to top.
4 Comment
5 Main loop is started and waiting for mouse and key board actoins.
Tkinter Widgets
Widget is a graphical user interface controls to interact between user and
computer. Tkinter gives different types of controls such as buttons, labels and
text boxes used in a GUI application. Tkinter widgets are described in the
following table. Most widegts can be seen in figure 14.1.
Widget Widget image Description
38
e Checkbutton Number of options can be selected using Python
Graphical User
check buttons. More than one choice can
Interface
be selected in grouped options Development
Entry A line of text can be entered using entry
widget
Frame A container to insert and organize other
widgets.
Label Caption of single line can be displayed
using label. Images may also insert to
label.
39
Data Handling, Mobile Option Description
Application & Gui
Development Using Active Background color when the cursor is on the button.
Python background
Active Foreground color when the cursor is on the button.
foreground
Bd width of the border. Default is 2.
Bg Normal background color.
command Calling function or method when the button is clicked.
Fg Colour of the text (foreground)
Font Type of the font used for label of the button.
Height Height of the text or image
Highlight The color of the focus highlight when the widget has focus.
color
Image Image to be attached and display
Justify Alignment of the text line - justify
CENTER Alignment of the text line - center
Padx Horizontal length of button through x axis can be sat.
Pady vertical length of button through x axis can be sat.
Relief Border style- button appear as SUNKEN, RAISED, GROOVE,
or RIDGE
State Can set the button as DISABLED or ACTIVE. It active when
the button is over.
underline Underline the relevant character, Default is -1, which means no
character is underlined.
Width Set the width of the button.
wraplength If this value is set to a positive number, the text lines will be
wrapped to fit within this length.
Example 14.2. This python program illustrates how to work with button.
1 #!/usr/bin/python
2
3 import Tkinter as tk
4 import tkMessageBox as bx
5 tp=tk.Tk()
6 def exbutton():
7 bx.showinfo("Python button example","Hello
8 World")
9 B=tk.Button(tp,text="Press this
10 button",command=exbutton)
B.pack()
tp.mainloop()tp.mainloop()
Figure 14.3. Message “Hello World” will appear when "Press this button" is
clicked
The output of the above program is shown in fig 14.3. When the button called
40 ‘Press this button’ is clicked, the message box ‘Hello World’ will appear.
e
Description of codes in line numbers of the program Python
Graphical User
Interface
9. import tkMessageBox module
Development
10. a function called exbutton
11. Text of the button is “Press this button” and button is assigned to
“B”. Function exbutton is invoked by clicking button.
Parameters:
• master: the parent window.
• options: : List of ususally used options are given below
Option Description
Bg background color
Bd Size of the border
The size of the border around the indicator. Default is 2
pixels.
command Invoking function when user change content
cursor Cursor of the mouse will change according to the given
cursor name (arrow, dot etc).
font Type of the font
exportselection By default, if you select text within an Entry widget, it is
automatically exported to the
clipboard To avoid this exportation, use exportselection=0.
Fg The color used to render the text.
highlightcolor The color of the focus highlight when the checkbutton has
the focus.
justify If the text contains multiple lines, this option controls how
the text is justified: CENTER, LEFT, or RIGHT.
relief With the default value, relief=FLAT, the checkbutton does
not stand out from its background. You may set this option
to any of the other styles .
Selectbackground Background color of the selected text
selectborderwidth The width of the border to use around selected text. The
default is one pixel.
selectforeground The foreground (text) color of selected text.
show Normally, the characters that the user types appear in the
entry. To make a .password. entry that echoes each
character as an asterisk, set show="*".
41
Data Handling, Mobile state The default is state=NORMAL, but you can use
Application & Gui
Development Using state=DISABLED to gray out the control and make it
Python unresponsive. If the cursor is currently over the
checkbutton, the state is ACTIVE.
Text variable In order to be able to retrieve the current text from your
entry widget, you must set this option to an instance of the
StringVar class.
Width The default width of a checkbutton is determined by the
size of the displayed image or text. You can set this option
to a number of characters and the checkbutton will always
have room for that many characters.
Xscroll command If you expect that users will often enter more text than the
onscreen size of the widget, you can link your entry widget
to a scrollbar.
When the above code is executed, it produces the output as show in the
Figure 14.4:
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.
42
e Python
Option Description Graphical User
anchor This options controls where the text is positioned if the widget Interface
Development
has more space than the text needs. The default is
anchor=CENTER, which centers the text in the available space.
Bg The normal background color displayed behind the label and
indicator.
Bitmap Set this option equal to a bitmap or image object and the label
will display that graphic.
Bd The size of the border around the indicator. Default is 2 pixels.
Cursor If you set this option to a cursor name (arrow, dot etc.), the
mouse cursor will change to that pattern when it is over the
checkbutton.
Font If you are displaying text in this label (with the text or text
variable option, the font option specifies in what font that text
will be displayed.
Fg If you are displaying text or a bitmap in this label, this option
specifies the color of the text. If you are displaying a bitmap, this
is the color that will appear at the position of the 1-bits in the
bitmap.
Height The vertical dimension of the new frame.
Image To display a static image in the label widget, set this option to an
image object.
Justify Specifies how multiple lines of text will be aligned with respect
to each other: LEFT for flush left, CENTER for centered (the
default), or RIGHT for right-justified.
Padx Extra space added to the left and right of the text within the
widget. Default is 1. pady Extra space added above and below
the text within the widget. Default is 1.
Relief Specifies the appearance of a decorative border around the label.
The default is FLAT; for other values. text To display one or
more lines of text in a label widget, set this option to a string
containing the text. Internal newlines ("\n") will force a line
break.
Textvariable To slave the text displayed in a label widget to a control variable
of class StringVar, set this option to that variable.
Under You can display an underline (_) below the nth letter of the text,
Line counting from 0, by setting this option to n. The default is
underline=-1, which means no underlining.
Example 14.4. This program illustrates how to program using label and grid.
1 import Tkinter as tk
2 m=tk.Tk()
3
4 tk.Label(m,text='First',bg="red").grid(row=0,column=0)
5 tk.Label(m,text='Second',bg="blue").grid(row=0,column=1)
tk.Label(m,text='Third',bg="green").grid(row=1,column=0)
m.mainloop()
The output of the above program is illustrated in the figure 14.5. Remember
you should write line 5 in one line.
43
Data Handling, Mobile
Application & Gui
Development Using
Python
Setting rows and columns of grid are shown in following table. Any widget
like entry, image can be arranged in grids.
Row=0, coloumn=0 Row=0, coloumn=1
Row=1, coloumn=0 Row=1, coloumn=1
Line number 3 of the above code is a Label and “Your sex:” is displayed.
There are two checkbuttons one for “male” and other for “female”.
Mainloop() waits for mouse and keyboard.
Grid property set label and check buttons 3 top rows of the “m” window.
Checkbutton for selection with align to the west
Checkbutton can be aligned using stick parameter in grid object. The
program to explain the grid sticky option of checkbutton is given in example
14.6 and the output screen is shown in figure 14.7.
Example 14.6 This program explains how to program using checkbutton with
grid sticky option.
44
e 1 from Tkinter import * #import Tkinter module
2 m=Tk() # Tk window assigned to m
3 Label(m,text="Your sex: ") .grid(row=0,sticky=W)
4 Checkbutton(m,text="male",variable=var1).grid(row=1,sticky=W)
5 Checkbutton(m,text="female",variable=var2).grid(row=2,sticky=W)
6 mainloop() #starts main loop- waiting for mouse and key board
(a) (b)
Male and female checkbuttons of figure 14.7 (a) are not aligned and figure
11.7 (b) shows the aligned checkbuttons. This can be done with sticky option
of grid manager. The above example has sticky=W i.e. aligned to left side.
Likewise, following options also can be used.
N, E, S, W, NE, NW, SE, and SW
Assigning checkbutton selection to variable
Example 14.7 This program describes how selections of checkbuttons are
assigned to variables.
45
Data Handling, Mobile Listbox
Application & Gui
Development Using
Python Listbox is the Tkinter standard list box to facilitate a list. List of provinces in
Sri Lanka created by using tkinter GUI library is shown in the figure 14.9.
User can select a province from the list of provinces.
Figure 14.9: List of provinces, user can select either province from the list
Python code for the output of the Figure 14.9 is given in example 14.8.
Example 14.8 program to describe listbox.
Line 3: l1 instance is derived from the Label class. Text of the label “l1” is
"Provinces of Sri Lanka".
l1=Label(master,text="Provinces of Sri Lanka")
46
e Python
Line 7: Append an item to the list. Graphical User
Interface
listbox.insert(END, "Central") Development
47
Data Handling, Mobile
Application & Gui
Development Using
Python
Line 3: Create a top level window as object of wx.Frame class. Caption and
size parameters are given in constructor.
window = wx.Frame(None,title="wxPython Frame",size=(300,200))
Line 4: Although other controls can be added in Frame object, their layout
cannot be managed. Hence, put a Panel object into the Frame.
panel=wx.Panel(window)
48
e
wx.Panel
wx.Panel class is derived from the wx.Window class. This class is inserted to
the wx.Frame class. Widgets such as button, text box etc. can be placed in
this class.
Sub classing the Frame -“Hello World” program with class
The GUI output in Figure 14.12 has a frame with the title “Hello World”.
49
Data Handling, Mobile
Application & Gui
Example 14.10 Program to create frame class called “Frame”.
Development Using 1 import wx
Python 2 class Frame(wx.Frame):
3 def __init__(self, title):
4 wx.Frame.__init__(self, None, title=title, size=(350,200))
5
6 app = wx.App(redirect=True)
7 top = Frame("Hello World")
8 top.Show()
9 app.MainLoop()
Line 3: The above title is received to the following class Frame and initiated
with the title.
def __init__(self, title):
Line 4: title of the line 3 is received to the wx.Frame and it initiated with
wx.Frame.__init__(self, None, title=title, size=(350,200))
50
e
Output of the Figure 14.13 is produced by running the code of the example
14.11.
Example 14.11 program code describes how to use textcontrols and
buttons of wxPython
1 import wx
2 class wxcal(wx.Frame):
3 def __init__(self, title):
4 wx.Frame.__init__(self, None, title=title,
pos=(150,150), size=(350,200))
5 panel = wx.Panel(self)
6 self.fno=wx.TextCtrl(panel, value="", pos=(10, 2),
size=(50,-1))
7 self.sno=wx.TextCtrl(panel, value="", pos=(70, 2),
size=(50,-1))
8 self.result= wx.TextCtrl(panel, -1,"", pos=(130, 2), .
size=(50,-1))
self.addbtn=wx.Button(panel, wx.ID_NONE, "+", pos =
9 (10,50) ,size=(50,-1))
self.addbtn.Bind(wx.EVT_BUTTON,self.addbtnclick)
10
self.subbtn=wx.Button(panel, wx.ID_NONE, "-",pos =
11
(70,50), size =(50,-1))
self.subbtn.Bind(wx.EVT_BUTTON,self.subbtnclick)
12
self.mulbtn=wx.Button(panel, wx.ID_NONE, "*", pos =
13
(130,50), size=(50,-1))
self.mulbtn.Bind(wx.EVT_BUTTON,self.mulbtnclick)
14
def addbtnclick(self,event):
15
self.result.SetValue(str(float(self.fno.GetValue())+
16
float(self.sno.GetValue()))
def subbtnclick(self,event):
17
self.result.SetValue(str(float(self.fno.GetValue())-
18
float (self.sno.GetValue())))
def mulbtnclick(self,event):
19
self.result.SetValue(str(float(self.fno.GetValue())*
20
float(self.sno.GetValue())))
app = wx.App(redirect=True)
21
top = wxcal("WX Calulator")
22
top.Show()
23
app.MainLoop()
24
Line 5: “panel” is a type of “wx.Panel” class. All the widgets such as text,
buttons are placed in panel. 51
Data Handling, Mobile panel = wx.Panel(self)
Application & Gui
Development Using
Python Line 6 to 8: Two (2) text boxes (wx. TextCtrl) named “fno” and “sno” are
placed in panel and their positions and sizes are specified as follows. There is
another text box named “result” is also placed in specified position and size.
self.fno=wx.TextCtrl(panel, value="", pos=(10, 2), size=(50,-1))
self.sno=wx.TextCtrl(panel, value="", pos=(70, 2), size=(50,-1))
self.result= wx.TextCtrl(panel, -1,"", pos=(130, 2), size=(50,-1))
Line 10 to 11: Button for addition named “addbtn” is a wx.Button class type.
Text of the button is “+” and position and size is as follows. This button has
no identification ( wx.ID_NONE). This button is bind to the method
“addbtnclick” on the click event of the button (wx.EVT_BUTTON ).
self.addbtn=wx.Button(panel, wx.ID_NONE, "+",pos=(10,50),size=(50,-1))
self.addbtn.Bind(wx.EVT_BUTTON,self.addbtnclick)
Line 13 to 17: Program codes for buttons for subtraction and multiplication
and their bindings.
self.subbtn=wx.Button(panel, wx.ID_NONE, "-",pos=(70,50),size=(50,-1))
self.subbtn.Bind(wx.EVT_BUTTON,self.subbtnclick)
Line 19 to 26: Methods to add, subtract and multiply values of fno and sno
and assigned to result are coded here.
def addbtnclick(self,event):
self.result.SetValue(str(float(self.fno.GetValue())+float(self.sno.GetV
alue())))
def subbtnclick(self,event):
self.result.SetValue(str(float(self.fno.GetValue())-
float(self.sno.GetValue())))
def mulbtnclick(self,event):
self.result.SetValue(str(float(self.fno.GetValue())*float(self.sno.Get
Value())))
Example 14.12 Program to display window and circle with red background
1 import wx
2 class drawgeo(wx.Frame):
3 def __init__(self, parent, title):
4 super(drawgeo, self).__init__(parent, title=title,size=(500,300))
self.InitUI()
5
def InitUI(self):
6 self.Bind(wx.EVT_PAINT, self.drawcle)
7
def drawcle(self,w):
8 dc = wx.PaintDC(self)
9 color=wx.Colour(255,0,0)
10 b=wx.Brush(color)
11 dc.SetBrush(b)
12 dc.DrawCircle(300,125,50)
13 app1 = wx.App()
14 top=drawgeo(None,"Draw circle")
15 top.Show()
16 app1.MainLoop()
17
The above window and circle with red background can be programmed by
using the following program. In this program, initially, create instance of wx
app and activate a wx.frame custom class to draw the circle.
Now we will study program code lines in the above program. For easy
reference, program is numbered at the left hand side column to the program.
1 import wx
Import wxPython modules into the program
16 app1 = wx.App()
Create an instance of wx app called app1
17 top=drawgeo(None,"Draw circle")
53
Data Handling, Mobile Create an instance of the custom class of wx.Frame named “drawgeo” with
Application & Gui
Development Using the title “Draw circle".
Python
18 top.Show()
Show the class “top”.
2 class drawgeo(wx.Frame):
Create a wx.Frame class named “drawgeo”
5 self.InitUI()
7 def InitUI(self):
Define InitUI() method
8 self.Bind(wx.EVT_PAINT, self.drawcle)
“drawcle” method of the class drawgeo is bound to the wx.EVT_PAINT event.
10 def drawcle(self,w):
Define the method “drawcle()”
11 dc = wx.PaintDC(self)
wx.PaintDC(self) is used to draw graphics in a client area.
12 color=wx.Colour(255,0,0)
Create an instance of wx.Colour called “color” whose colour is (255,0,0). i.e.
red.
1 b=wx.Brush(color)
3
Create an instance of wx.Brush called “b” whose colour is “color”. wx.Brush is
used to fill
background colur of the object.
14 dc.SetBrush(b)
Set the brush of the wx.PaintDC class called “dc”.
15 dc.DrawCircle(300,125,50)
Draw the circle with x axis point, y axis point and radius
54
e
Python
wxPython GUI visual Designer tools Graphical User
Interface
Coding GUI windows is a very difficult and time cosuming effort. Therefore, Development
there are few visual GUI designer tools available for rapid and quick GUI
application development. They are wxFormBuilder, wxDesigner, wxGlade,
BoaConstructor, gui2py.
Activity14.1
1) Write a GUI program using Tkinter libraries to input two boolean values
(0 or 1) and select a boolean operation from set of boolean operations
AND, OR, NAND, NOR, XOR. Result should be printed in a text box
next to the boolean selection box.
2) Write a GUI program using wxPython libraries to input 2 boolean values
(0 or 1) and select a boolean operation from set of boolean operations
AND, OR, NAND, NOR, XOR. Result should be printed in a text box
next to the boolean selection box.
Check Your Progress
Q-1 Write Tkinter lines of codes to embed following on a form
a) Label
b) Check Button
c) Text entry
d) Button
Q-2 Classify the modules and sub-modules in wxPython.
14.8 SUMMARY
In this unit you learned to identify elements of GUI, different types of python
related packages for GUI development, GUI implement using Tkinter
standard library and wxPython. Then you learned how to invoke widgets of
GUI with methods in user defined classes.
55