Python Unit 5.1
Python Unit 5.1
Python Unit 5.1
What is a GUI?
A Graphical User Interface(GUI) is the first thing your user sees and interacts
with when he opens your application or website. Having a good GUI goes a long way in
increasing your platform’s reputation and user count. A user interface usually includes
a host of visual elements like icons, buttons, graphics, displayed text, and several other
forms of input, like checkbox, text input boxes, and such.
It’s the combination of all these elements that makes up a vital part of your
application or website’s user experience. Input to these visual elements can be from
the usual mediums, such as keyboards, mice, and touchscreens.
Python provides various options for developing graphical user interfaces (GUIs). Most
important are listed below.
Tkinter − Tkinter is the Python interface to the Tk GUI toolkit shipped with
Python. We would look this option in this chapter.
wxPython − wxPython is essentially a Python extension module that acts as a
wrapper for the wxWidgets API. wxPython allows Python developers to create
native user interfaces that add zero additional overhead to the application. The
cross-platform capabilities of wxPython allow deployment to platforms like
Windows, Mac OS, Linux, and Unix-based systems with little to no
modifications.
JPython − JPython is a Python port for Java which gives Python scripts
seamless access to Java class libraries on the local machine.
PyQt -The PyQt package is built around the Qt framework, which is a cross-
platform framework used for creating a plethora of applications for various
platforms. The PyQt5 package includes a detailed set of bindings for Python
based on the latest version v5 of the Qt application framework. PyQt5 is
also fully cross-platform. By leveraging the power of PyQt5, developers can
build applications for platforms like Windows, Mac, Linux, iOS, Android, and
more.
Kivy-Written with a mix of Python and Cython, Kivy is an open-source GUI
framework for building some of the most intuitive user interfaces encompassing
multi-touch applications that implement Natural User Interface(NUI).
With Kivy, interface designers can code once and deploy to multiple platforms, while
the built-in support for OpenGL ES 2 allows them to use modern and powerful
graphics and design techniques. The most common use of the Kivy GUI
framework in the real-world can be seen in our Android and iOS applications. Other
widespread implementations of the framework can be seen in the user interfaces
of Linux, Windows, Raspberry Pi, and Mac OS devices.
PySide2- PySide2 is built by the same company that gave us the widely popular
application development framework Qt. Upon looking closely, you’ll come across
the term “Qt for Python Project”, which is nothing but the task of porting PySide
to support Qt5, whereas the framework itself is now being called PySide2.
PyGTK - PyGTK is a set of wrappers written in Python and C for GTK + GUI
library. It is part of the GNOME project. It offers comprehensive tools for building
desktop applications in Python. This tutorial discusses the basic functionalities of
the different widgets found in the toolkit.
Comparison between Kivy and Tkinter
Kivy Tkinter
Kivy is an open-source and free python framework Tkinter is also another Python library for
for developing user interface apps along with developing GUI apps which is usually a
multi-touch apps. combination of the Tk GUI toolkit and Python
GUI framework.
To install Kivy, we need to use the pip command There is no need of installing Tkinter as it is
where pip needs to be installed in Python IDE. an in-built Python Standard library for GUI
development desktop apps.
In Kivy toolkit is usually developed, backed up, In Tkinter, there is a Tk toolkit that is
and then used in any commercial products. provided already with this Tkinter standard
Python library. We just need to import Tkinter
as tk.
These are used to develop mobile apps or multi- Tkinter is mainly used for developing
touch apps also along with desktop apps. desktop apps as it does not provide any
features for developing mobile apps, as in
Kivy.
Kivy can be run on Microsoft Windows, Raspberry Tkinter can be run on platforms such as
Pi, Android, iOS, and OS X or any other Microsoft Windows, Linux, Unix, and Mac OS
supported platforms for Kivy. X install versions of Python.
Kivy is an ope-source and 100% free version Tkinter is also an open-source, free software
under MITL that is Massachusetts Institute of version under PL that is Python License for
Technology License for developing commercial developing commercial products or apps.
apps or products.
Kivy is widely used for developing more dynamic Tkinter is mainly used by the developers that
and advanced apps in Python programming. are a beginner in developing GUI’s ad wants
to develop only GUI’s for computers.
Comparison of Kivy vs PyQt
Kivy PyQt
Kivy is also a cross-platform for developing mobile PyQt is a cross-platform which has a Python
applications and other multi-touch applications, binding for developing desktop apps with its
Hence Kivy can be defined as a Python built-in widgets and tools along with robust SQL
framework or Python library for developing user database support. Hence PyQt is defined as a
interface mobile and multi-touch applications that Python GUI framework for developing mostly
are open source and free. desktop software with the set of Python
versions v2 and v3 binding which is also free
and open source.
It can be used on Windows, Android, Raspberry It can be used on Windows, Android, Raspberry
Pi, iOS, and OS X or any other supported Pi, Linux, and Mac or any other supported
platforms for Kivy, and tools it can be integrated platforms for PyQt, and tools that can be
with Kivy are Python, Windows, Mac, and Linux. integrated with PyQt are Linux, Linux Mint, and
Windows.
Kivy is a 100% free version under MITL which PyQt is a free version under GPL which means
means Massachusetts Institute of Technology General Public License that is it is free only
License and can also be used in developing when the code written by you or the developer
commercial products. is not sold and if the code needs to be sold then
it no longer a free version in PyQt as it
considers it as commercial so we need to do
the payments or purchase it.
Kivy has a graphic engine that is built over In PyQt it has PyQtgraph which is built on
OpenGL with the most modern and fast pipelines. PyQt4 or PySide or NumPy which also having
fast pipelines as it has heavy leverage of
NumPy libraries.
It provides a toolkit that has 20 widgets such as It Provides various UI components such as
buttons, labels, Layouts, etc which is highly widgets which include buttons, menus, labels,
extensible which are written and test in Cython tables, etc, and all other designable widgets
using C and regression tests respectively. that are compatible with PyQt as QT provides
all these UI components in Python.
It can also use some input, devices, and protocols It also can be used with several input devices
such as Linux Kernel HID, Magic Mouse, Mtdev, such as keyboards or mouse and it does not
can also use some input, devices, and protocols offer much as in Kivy frameworks.
such as Linux Kernel HID, Magic Mouse, Mtdev,
etc with other input devices like mouse, dual
mouse Apple’s products, TUIO, etc.
The main drawback of Kivy is it is not that suitable The main drawback of PyQt is not available
for compiling or accessing complex application with any specific resources which mean it can
codes as it needs the combination of py and kV be used in the data in C++ only where it
languages along with the help of specific sometimes may make developers complex in
algorithms. designing as it needs more experience in C++.
This provides Kivy language which has better In PyQt, Qt is not any programming language
syntax and representation of all functionalities in as it is a tool but it mainly supports C++
the Kivy program with more precise and organized programming language to develop Qt.
in tree format.
Kivy is not recommendable for the applications PyQt is mostly recommended for building truly
which have native look for the desktops that are native applications that mostly rely on desktop
there would not be a proper match in appearance software or applications which means it most
or behavior-wise for Mac app on Mac suitable for desktop applications.
This mostly provides applications that work better This mostly provides applications that work
in mobile applications and other multi-touch or better with desktop applications or software
user interface application but comparatively less than any mobile applications or multi-touch
in desktop applications. applications.
There are many other interfaces available, which you can find them on the net.
Tkinter Programming
Tkinter is the standard GUI library for Python. Python when combined with Tkinter
provides a fast and easy way to create GUI applications. Tkinter provides a powerful
object-oriented interface to the Tk GUI toolkit.
Creating a GUI application using Tkinter is an easy task. All you need to do is perform
the following steps −
Import the Tkinter module.
Create the GUI application main window.
Add one or more of the above-mentioned widgets to the GUI application.
Enter the main event loop to take action against each event triggered by the
user.
Example
import Tkinter
top = Tkinter.Tk()
# Code to add widgets will go here...
top.mainloop()
Tkinter Widgets
Tkinter provides various controls, such as buttons, labels and text boxes used in a GUI
application. These controls are commonly called widgets.
There are currently 15 types of widgets in Tkinter. We present these widgets as well as
a brief description in the following table −
Sr.No. Operator & Description
1 Button
The Button widget is used to display buttons in your application.
2 Canvas
The Canvas widget is used to draw shapes, such as lines, ovals, polygons and
rectangles, in your application.
3 Checkbutton
The Checkbutton widget is used to display a number of options as checkboxes.
The user can select multiple options at a time.
4 Entry
The Entry widget is used to display a single-line text field for accepting values
from a user.
5 Frame
The Frame widget is used as a container widget to organize other widgets.
6 Label
The Label widget is used to provide a single-line caption for other widgets. It can
also contain images.
7 Listbox
The Listbox widget is used to provide a list of options to a user.
8 Menubutton
The Menubutton widget is used to display menus in your application.
9 Menu
The Menu widget is used to provide various commands to a user. These
commands are contained inside Menubutton.
10 Message
The Message widget is used to display multiline text fields for accepting values
from a user.
11 Radiobutton
The Radiobutton widget is used to display a number of options as radio buttons.
The user can select only one option at a time.
12 Scale
The Scale widget is used to provide a slider widget.
13 Scrollbar
The Scrollbar widget is used to add scrolling capability to various widgets, such as
list boxes.
14 Text
The Text widget is used to display text in multiple lines.
15 Toplevel
The Toplevel widget is used to provide a separate window container.
16 Spinbox
The Spinbox widget is a variant of the standard Tkinter Entry widget, which can be
used to select from a fixed number of values.
17 PanedWindow
A PanedWindow is a container widget that may contain any number of panes,
arranged horizontally or vertically.
18 LabelFrame
A labelframe is a simple container widget. Its primary purpose is to act as a spacer
or container for complex window layouts.
19 tkMessageBox
This module is used to display message boxes in your applications.
Let us study these widgets in detail –
Standard attributes
Let us take a look at how some of their common attributes.such as sizes, colors and
fonts are specified.
Dimensions
Colors
Fonts
Anchors
Relief styles
Bitmaps
Cursors
Let us study them briefly −
Geometry Management
All Tkinter widgets have access to specific geometry management methods, which
have the purpose of organizing widgets throughout the parent widget area. Tkinter
exposes the following geometry manager classes: pack, grid, and place.
The pack() Method − This geometry manager organizes widgets in blocks before
placing them in the parent widget.
The grid() Method − This geometry manager organizes widgets in a table-like
structure in the parent widget.
The place() Method − This geometry manager organizes widgets by placing
them in a specific position in the parent widget.
Tkinter Button
The Button widget is used to add buttons in a Python application. These buttons can
display text or images that convey the purpose of the buttons. You can attach a
function or a method to a button which is called automatically when you click the
button.
Syntax
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.
Sr.No. Option & Description
1
activebackground
Background color when the button is under the cursor.
2
activeforeground
Foreground color when the button is under the cursor.
3
bd
Border width in pixels. Default is 2.
4
bg
Normal background color.
5
command
Function or method to be called when the button is clicked.
6
fg
Normal foreground (text) color.
7
font
Text font to be used for the button's label.
8
height
Height of the button in text lines (for textual buttons) or pixels (for images).
9
highlightcolor
The color of the focus highlight when the widget has focus.
10
image
Image to be displayed on the button (instead of text).
11
justify
How to show multiple text lines: LEFT to left-justify each line; CENTER to center
them; or RIGHT to right-justify.
12
padx
Additional padding left and right of the text.
13
pady
Additional padding above and below the text.
14
relief
Relief specifies the type of the border. Some of the values are SUNKEN, RAISED,
GROOVE, and RIDGE.
15
state
Set this option to DISABLED to gray out the button and make it unresponsive. Has
the value ACTIVE when the mouse is over it. Default is NORMAL.
16
underline
Default is -1, meaning that no character of the text on the button will be
underlined. If nonnegative, the corresponding text character will be underlined.
17
width
Width of the button in letters (if displaying text) or pixels (if displaying an image).
18
wraplength
If this value is set to a positive number, the text lines will be wrapped to fit within
this length.
Methods
Example
import Tkinter
import tkMessageBox
top = Tkinter.Tk()
def helloCallBack():
tkMessageBox.showinfo( "Hello Python", "Hello World")
B.pack()
top.mainloop()
When the above code is executed, it produces the following result –
Tkinter 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
Parameters
arc − Creates an arc item, which can be a chord, a pieslice or a simple arc.
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)
polygon − Creates a polygon item that must have at least three vertices.
oval = canvas.create_polygon(x0, y0, x1, y1,...xn, yn, options)
Example
top = Tkinter.Tk()
C.pack()
top.mainloop()
When the above code is executed, it produces the following result −
Tkinter Checkbutton
The Checkbutton widget is used to display a number of options to a user as toggle
buttons. The user can then select one or more options by clicking the button
corresponding to each option.
You can also display images in place of text.
Syntax
Parameters
Methods
Following are commonly used methods for this widget −
Sr.No. Method & Description
1 deselect()
Clears (turns off) the checkbutton.
2 flash()
Flashes the checkbutton a few times between its active and normal colors, but
leaves it the way it started.
3 invoke()
You can call this method to get the same actions that would occur if the user
clicked on the checkbutton to change its state.
4 select()
Sets (turns on) the checkbutton.
5 toggle()
Clears the checkbutton if set, sets it if cleared.
Example
Try the following example yourself −
from Tkinter import *
import tkMessageBox
import Tkinter
top = Tkinter.Tk()
CheckVar1 = IntVar()
CheckVar2 = IntVar()
C1 = Checkbutton(top, text = "Music", variable = CheckVar1, \
onvalue = 1, offvalue = 0, height=5, \
width = 20)
C2 = Checkbutton(top, text = "Video", variable = CheckVar2, \
onvalue = 1, offvalue = 0, height=5, \
width = 20)
C1.pack()
C2.pack()
top.mainloop()
When the above code is executed, it produces the following result −
Tkinter Entry
The Entry widget is used to accept single-line text strings from a user.
If you want to display multiple lines of text that can be edited, then you should
use the Text widget.
If you want to display one or more lines of text that cannot be modified by the
user, then you should use the Label widget.
Syntax
Parameters
Methods
Following are commonly used methods for this widget –
Example
from Tkinter import *
top = Tk()
L1 = Label(top, text="User Name")
L1.pack( side = LEFT)
E1 = Entry(top, bd =5)
E1.pack(side = RIGHT)
top.mainloop()
When the above code is executed, it produces the following result –
Tkinter Frame
The Frame widget is very important for the process of grouping and organizing other
widgets in a somehow friendly way. It works like a container, which is responsible for
arranging the position of other widgets.
It uses rectangular areas in the screen to organize the layout and to provide padding of
these widgets. A frame can also be used as a foundation class to implement complex
widgets.
Syntax
Parameters
Example
Try the following example yourself −
from Tkinter import *
root = Tk()
frame = Frame(root)
frame.pack()
bottomframe = Frame(root)
bottomframe.pack( side = BOTTOM )
root.mainloop()
When the above code is executed, it produces the following result −
Tkinter Label
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.
It is also possible to underline part of the text (like to identify a keyboard shortcut) and
span the text across multiple lines.
Syntax
Parameters
Example
Try the following example yourself −
from Tkinter import *
root = Tk()
var = StringVar()
label = Label( root, textvariable=var, relief=RAISED )
Tkinter Radiobutton
This widget implements a multiple-choice button, which is a way to offer many possible
selections to the user and lets user choose only one of them.
In order to implement this functionality, each group of radiobuttons must be associated
to the same variable and each one of the buttons must symbolize a single value. You
can use the Tab key to switch from one radionbutton to another.
Syntax
Parameters
Example
Try the following example yourself −
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 )
label = Label(root)
label.pack()
root.mainloop()
When the above code is executed, it produces the following result –
Tkinter Text
Text widgets provide advanced capabilities that allow you to edit a multiline text and
format the way it has to be displayed, such as changing its color and font.
You can also use elegant structures like tabs and marks to locate specific sections of
the text, and apply changes to those areas. Moreover, you can embed windows and
images in the text because this widget was designed to handle both plain and
formatted text.
Syntax
Parameters
Methods
Text objects have these methods −
Sr.No. Methods & Description
1 delete(startindex [,endindex])
This method deletes a specific character or a range of text.
2 get(startindex [,endindex])
This method returns a specific character or a range of text.
3 index(index)
Returns the absolute value of an index based on the given index.
4 insert(index [,string]...)
This method inserts strings at the specified index location.
5 see(index)
This method returns true if the text located at the index position is visible.
Text widgets support three distinct helper structures: Marks, Tabs, and Indexes −
Marks are used to bookmark positions between two characters within a given text. We
have the following methods available when handling marks –
Example
Try the following example yourself −
from Tkinter import *
def onclick():
pass
root = Tk()
text = Text(root)
text.insert(INSERT, "Hello.....")
text.insert(END, "Bye Bye.....")
text.pack()