[go: up one dir, main page]

0% found this document useful (0 votes)
56 views21 pages

Unit 14

This document discusses Python graphical user interface (GUI) development. It introduces Tkinter and wxPython, two popular packages for building GUIs in Python. Tkinter is the standard GUI library that is bundled with Python, while wxPython is an open-source cross-platform GUI package. The document provides examples of creating simple GUIs using Tkinter and discusses various Tkinter widgets like buttons, labels, and text boxes that can be used to build the GUI. It also includes links to videos that demonstrate Tkinter and wxPython GUI development.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
56 views21 pages

Unit 14

This document discusses Python graphical user interface (GUI) development. It introduces Tkinter and wxPython, two popular packages for building GUIs in Python. Tkinter is the standard GUI library that is bundled with Python, while wxPython is an open-source cross-platform GUI package. The document provides examples of creating simple GUIs using Tkinter and discusses various Tkinter widgets like buttons, labels, and text boxes that can be used to build the GUI. It also includes links to videos that demonstrate Tkinter and wxPython GUI development.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

e

UNIT 14 PYTHON GRAPHICAL USER


INTERFACE DEVELOPMENT

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

Layouts: layouts to arrange widgets


import: Import the necessary modules to python code
Tkinter: Standard python GUI library
wxPython: Free and open source GUI package for python

14.4 GRAPHICAL USER INTERFACE (GUI)


When you work with computer, you need to interact with it in many ways
such as clicking on various icons, selecting from menus, right clicking,
double clicking, writing text in word processor, inserting pictures, inserting
movies etc. All these works are processed in computer through hardware.
User Interface is the space where interctions between you and the computer
hardware.
The first user interface that came with computers, was a command-line
interface where you could interact with the computer by typing commands on
the keyboard. Typing commands was a very difficult task and user needs to
have a very good hardware background. Later, graphical representations of
such commands were created to interact with any user which are called
Graphical User Interface (GUI).
Visual indications of GUI which can be implemented by python language are
illustrated in fig. 14.1.

Figure 14.1 Visualization of GUI

Before we proceed, let's define some of the common terms.


Window – it is a rectangular zone on computer screen
top-level window - is an independent window within an application. One
application may have many top level windows. Many children windows can
be created within top level window. When you close a child window it will
go back to the parent window
What is shown in figure 14.1 as the root window is a top level window.

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.

Frame - Rectangular area which contains other widgets to organize different


layouts.

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.

14.5 DIFFERENT TYPES OF PACKAGES


FOR GUI DEVELOPMENT IN PYTHON
There are many tool kit options available for developing graphical user
interface (GUI) . Most popular are given below:
Tkinter - GUI toolkit given with python is Tkinter. All the other GUI tool
kits for python can be used as alternatives to the Tkinter.
PyGTK – permits to write GTK programs in python and has a lot of
widegets than Tkinter.
PyQT – is a set of python software libraries for Qt Framework.Qt is an
extensive C++ GUI application development framework that is available for
Unix, Windows and Mac OS X.
wxPython – is a set of python software libraries to create wxWidgets.
Kivy – is an open source cross platform for developing mobile apps using
python. Mobile apps can be developed for andriod, iOS, linux and windows.
GUI program development with Tkinter and wxPython is described next,
whereas program development with Kivy GUI is described in unit 15.

14.6 TKINTER (GUI TOOLKIT THAT


COMES WITH PYTHON)
GUI library for python given with the python programming langauage is
Tkinter. GUI applications can be created easily and quickly using Tkinter.
Strong object oriented widgets to the Tk GUI are given by Tkinter
Creating GUI using Tkinter
Method of programming Tkinter GUI window is described by the example
14.1.

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()

Window created by the above program is illustrated by Figure 14.2.

Figure 14.2. Tkinter window


Code line of the above program are explained as follows

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.

Video 14: Creating GUI for Python with Tkinter


This video will demostrate how to create a GUI with Tkinter. You may watch
this Video carry out the tasks listed below in creating widgets, buttons etc.
URL https://youtu.be/jcgyfeZsaTc

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

Canvas is a rectangle area which used to display


and edit graphics. For example – lines,
polygen, rectangle

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.

Listbox list of options can be provided listbox

Menubutton Menu options can be displayed in an


application.
Menu Various commands contained in Menu
buttons are given to user.
Message For displaying mulitline text fields to
take values from user
Radiobutton Only one option at a time can be
selected by Radio button.

Scale A number value can be changed by


moving knob of a slider.
Scrollbar Scrolling facility can be added for
various widegets.
Text Multiple line of text can be displayed.

Toplevel Separate window container can be


provided.
LabelFrame Works as a container for complex
window layouts.
tkMessageBox Message box can be inserted to
application.

Using Button widget in window


Function or a method can be attached to a button which is called
automatically when the button is clicked.
Here is the simple syntax to create this widget:
w = Button ( master, option=value, ... )
Parameters:
• master: Parent window
• options: Options are listed in the Following table.

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.

Using Entry widget in window


Single line text strings can be entered using entry widget. Text widget can be
used to enter multiple lines and label widget is used to display one or more
lines of text but cannot edit.
Syntax
Here is the simple syntax to create this widget −

w = Entry( master, option, ... )

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.

Example 14.3. This program describes how to use a Tkinter entry in a


program.
1 from Tkinter import *
2 tp=Tk()
3 la1=Label(tp,text="User ID")
4 la1.pack(side=LEFT)
5 en1=Entry(tp,bd=6)
6 en1.pack(side=RIGHT)
7 tp.mainloop()

When the above code is executed, it produces the output as show in the
Figure 14.4:

Figure 14.4 Text entry


Using Label widget in window
This widget implements a display box where you can place text or images.
The text displayed by this widget can be updated at any time you want.
Syntax
w = Label ( master, option, ... )

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

Figure 14.5 output of the above program

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

Using Check button widget : Checkbutton for selection


Output of running the code in example 14.5 is shown in the Figure 14.6

Figure 14.6 Check button entry

Example 14.5 Program to describes how to program using label and


checkbutton in Tkinter GUI.
1 from Tkinter import * #import Tkinter module
2 m=Tk() # Tk window assigned to m
3 Label(m,text="Your sex: ") .grid(row=0)
4 Checkbutton(m,text="male").grid(row=1)
5 Checkbutton(m,text="female").grid(row=2)
6 mainloop() #starts main loop- waiting for mouse and #key
board

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)

Figure 14.7 Left alignments of check boxes

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.

1 from Tkinter import * #import Tkinter module


2 m=Tk() # Tk window assigned to m
3 def var_states():
4 print var1.get()
5 print var2.get()
6 Label(m,text="Your sex: ") .grid(row=0,sticky=W)
7 var1=IntVar()
8 Checkbutton(m,text="male",variable=var1).grid(row=1,sticky=W)
9 var2=IntVar()
10 Checkbutton(m,text="female",variable=var2).grid(row=2,sticky=W)
11 Button(m, text='Show', command=var_states).grid(row=4, sticky=W,
12 pady=4)
mainloop() #starts main loop- waiting for mouse and key board

Command of the button is binded to the var_states function. Variable values


in three different marks of checkbuttons are displayed in figure 14.8.

Figure 14.8: Three different values in checkbutton

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.

1 from Tkinter import *


2 master = Tk()
3 l1=Label(master,text="Provinces of Sri Lanka")
4 l1.pack()
5 listbox = Listbox(master)
6 listbox.pack()
7 listbox.insert(END, "Central")
8 for item in ["Eastern",
9 "North Central",
10 "Northern",
11 "North Western",
12 "Sabaragamuwa",
13 "Southern",
14 "Uva",
15 "Western"]:
16 listbox.insert(END, item)
17 mainloop()

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")

Line 5: listbox instance is derived from the Listbox class.


listbox = Listbox(master)

46
e Python
Line 7: Append an item to the list. Graphical User
Interface
listbox.insert(END, "Central") Development

Line 8 to 16: Append all other items to list.


for item in ["Eastern",
"North Central",
"Northern",
"North Western",
"Sabaragamuwa",
"Southern",
"Uva",
"Western"]:
listbox.insert(END, item)

14.7 GUI WITH WXPYTHON


WxPython is a free and open source cross platform GUI toolkit package. It
can be downloaded from the official website http://wxpython.org. It consists
of wxObject class, which is the base for all classes in the API. Control
module contains all the widgets used in GUI application development. For
example, wx.Button, wx.StaticText (analogous to a label), wx.TextCtrl
(editable text control), etc.

Figure 14.10 wxPython basic ad sub modules

“wxPyton” contains five basic modules, windows, Graphics Device Interface


(GDI), Misc, Core and Controls. Basic modules and some of sub modules are
depicted in figure 14.10.
Basic wxPython GUI development

GUI in Figure 14.11 has a frame and a “Hello world” text.

47
Data Handling, Mobile
Application & Gui
Development Using
Python

Figure 14.11. basic wxPython program output

Output in Figure 14.11 is produced by the code in example 14.9.


Example 14.9 Program to exaplain to create wxPython GUI window
1 import wx
2 app = wx.App()
3 window = wx.Frame(None,title="wxPython Frame",size=(300,200))
4 panel=wx.Panel(window)
5 label=wx.StaticText(panel,label="Hello World",pos=(100,50))
6 window.Show(True)
7 app.MainLoop()

Let us anayse the above code to understand what it does.


Line 1: Import the wx module.
import wx

Line 2 : Define an object of Application class.


app = wx.App()

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)

Line 5: Add a StaticText object to display ‘Hello World’ at a desired position


inside the window.
label=wx.StaticText(panel,label="Hello World",pos=(100,50))

Line 6: Activate the frame window by show() method.


window.Show(True)

Line 7: Enter the main event loop of Application object.


app.MainLoop()

48
e

Line 3,4,5 of the above program include wx classes called wx.Frame,


wx.Panel and wx.StaticText.
Top level window classes (wx.Frame and wx.Panel) : wx.Frame
wx.Frame class is a top level window class. Higher level to this class is
wx.Window. You can change its size and position. It is a container widget. It
means that it can contain any window that is not a frame or dialog. wx.Frame
has a title bar, borders and a central container area. The title bar and borders
are optional. They can be removed by various flags.
wx.Frame Class has a default constructor with no arguments. It also has an
overloaded constructor with the following parameters:
wx.Frame (parent, id, title, pos, size, style, name)

window=wx.Frame(None, -1, “Hello”, pos=(10,10), size=(300,200), style=


wxDEFAULT_FRAME_STYLE, name=”frame”)

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”.

Figure 14.12: basic GUI of wxPython

Output of the Figure 14.12 is produced by running the program in example


14.10.

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()

Let us analyse code lines of the example 14.10 to understand creation of


frame class.
Line 2: class Frame is derived from the wx.Frame.
class Frame(wx.Frame):

Line 7: class Frame is called with the title “Hello World”


top = Frame("Hello World")

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))

Video 16: Python GUI with WxFrame


This video will demostrate how to create a GUI with WxFramework. You
may watch this Video to create the calculator example.
URL : https://youtu.be/je7l6OMdjFU

Adding content to the frame with Calculator example


Calculator GUI in Figure 14.13 has 3 text boxes for inputting 2 numbers and
for displaying result. There are three (3) buttons for calculating addition,
subtraction and multiplication.

50
e

Figure 14.13: Calculation of 2 variables

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 2: Class wxcal is created and ts base class is wx.Frame.


class wxcal(wx.Frame):

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)

self.mulbtn=wx.Button(panel, wx.ID_NONE, "*",pos=(130,50),size=(50,-1))


self.mulbtn.Bind(wx.EVT_BUTTON,self.mulbtnclick)

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())))

WxPython Graphics Drawing Interface (GDI)


GDI in wxPython offers objects required for drawing shape, text and image
like Colour, Pen, Brush and Font. It is used to interact with graphic devices
such as monitor, printer or a file. It consists of 2D vector graphics, fonts and
images. Objects called “device context” (DC) should be created to start
drawing graphics. It represents number of devices in a generic way.
wx.DC classes are
# wxBufferedDC
# wxBufferedDC
# wxBufferedPaintDC
# wxPostScriptDC
# wxMemoryDC
# wxPrinterDC
52 # wxScreenDC
e Python
# wxClientDC
Graphical User
# wxPaintDC Interface
# wxWindowDC Development

Drawing a circle with background colour of red in a window titled “Draw


circle” is shown in Figure 14.14.

Figure 14.14 Drawing circle using GDI

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”

3 def __init__(self, parent, title):


Define the init method whose parameters are title and parameters belongs to
supper class
“wx.Frame”.

4 super(drawgeo, self).__init__(parent, title=title,size=(500,300))


Title of the super class is "Draw circle" and size is (500,300)

5 self.InitUI()

Start InitUI method.

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.

14.9 FURTHER READING


1) kivy.org – official site
2) TutorialsPoint (I) Pvt. Ltd., PYTHON programming language,
https://www.tutorialspoint.com/python/python_tutorial.pdf

14.10 ANSWER TO CHECK YOUR


PROGRESS
Ans-1 Refer section 14.6

Ans-2 Refer section 14.7

55

You might also like