Introduction to Python GUI
Python provides various options for developing graphical user interfaces
(GUIs). Most important are listed below.
Tkinter: It is the easiest among all to get started with. It is Python’s
standard GUI (Graphical User Interface) package. It is the most
commonly used toolkit for GUI Programming in Python.
JPython: It is the Python platform for Java that is providing Python
scripts seamless access o Java class Libraries for the local machine.
wxPython: It is open-source cross-platform GUI toolkit written in C++. It
one of the alternatives to Tkinter, which is bundled with Python.
There are many other interfaces available for GUI. But these are the
most commonly used ones.
Python GUI Programming - Tkinter
It is the standard GUI toolkit for Python.
It was written by Fredrik Lundh.
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.
Tkinter is an acronym for "Tk interface".
Note: Tkinter comes pre-installed with Python3, and you need not bother
about installing it.
Python GUI Programming - Tkinter
Install Tkinter
To see if you have Tkinter, launch python; then at the Python prompt,
type:
import Tkinter
Or in Python 3: import tkinter
sudo apt-get install python-tk (for version 2)
sudo apt-get install python3-tk (for versoin 3)
Python GUI Programming - Tkinter
There is method used you the user need to remember while creating the
Python application with GUI.
Tk(screenName=None, baseName=None, className=’Tk’, useTk=1):
The basic code used to create the main window of the application is:
m=tkinter.Tk() where m is the name of the main window object
Steps:
First, you import the key component, i.e., the Tkinter module.
As a next step, you initialize the window manager with the tkinter.Tk()
method and assign it to a variable. This method creates a blank
window with close, maximize, and minimize buttons on the top as a
usual GUI should have.
Then as an optional step, you will Rename the title of the window as
you like with window.title(title_of_the_window).
Next, you make use of a widget called Label, which is used to insert
some text into the window.
Then, you make use of Tkinter's geometry management attribute
called pack() to display the widget in size it requires.
Finally, as the last step, you use the mainloop() method to display the
window until you manually close it. It runs an infinite loop in the
backend.
Python GUI Programming - Tkinter
mainloop():
There is a method known by the name mainloop() is used when you are
ready for the application to run.
mainloop() is an infinite loop used to run the application, wait for an
event to occur and process the event till the window is not closed.
m.mainloop()
Example:
import tkinter
m = tkinter.Tk()
m.mainloop()
Python GUI Programming - Tkinter
tkinter also offers access to the geometric configuration of the widgets
which can organize the widgets in the parent windows.
There are mainly three geometry manager classes class.
pack() method:
It organizes the widgets in blocks before placing in the parent widget.
grid() method:
It organizes the widgets in grid (table-like structure) before placing in
the parent widget.
place() method:
It organizes the widgets by placing them on specific positions directed
by the programmer.
Pack() method
Pack is the easiest to use of the three geometry managers of Tk and
Tkinter.
Instead of having to declare precisely where a widget should appear on
the display screen, we can declare the positions of widgets with the
pack command relative to each other.
The pack command takes care of the details.
Though the pack command is easier to use, this layout managers is
limited in its possibilities compared to the grid and place mangers.
For simple applications it is definitely the manager of choice.
For example simple applications like placing a number of widgets side
by side, or on top of each other.
Pack() method
from Tkinter import *
root = Tk()
Label(root, text="Red Sun", bg="red", fg="white").pack()
Label(root, text="Green Grass", bg="green", fg="black").pack()
Label(root, text="Blue Sky", bg="blue", fg="white").pack()
mainloop()
Pack() method
Fill:
If you want to make the widgets as wide as the parent widget, you have to
use the fill=X option:
from Tkinter import *
root = Tk()
w = Label(root, text="Red Sun", bg="red", fg="white")
w.pack(fill=X)
w = Label(root, text="Green Grass", bg="green", fg="black")
w.pack(fill=X)
w = Label(root, text="Blue Sky", bg="blue", fg="white")
w.pack(fill=X)
mainloop()
Pack() method
Padding:
The pack() manager knows four padding options, i.e. internal and
external padding and padding in x and y direction:
padx External padding, horizontally
pady External padding, vertically
ipadx Internal padding, horizontally.
ipady Internal padding, vertically
Pack() method
padx External padding, horizontally
from tkinter import *
root = Tk()
w = Label(root, text="Red Sun", bg="red", fg="white")
w.pack(fill=X,padx=10)
w = Label(root, text="Green Grass", bg="green", fg="black")
w.pack(fill=X,padx=10)
w = Label(root, text="Blue Sky", bg="blue", fg="white")
w.pack(fill=X,padx=10)
mainloop()
Pack() method
pady External padding, vertically
from tkinter import *
root = Tk()
w = Label(root, text="Red Sun", bg="red", fg="white")
w.pack(fill=X,pady=10)
w = Label(root, text="Green Grass", bg="green", fg="black")
w.pack(fill=X,pady=10)
w = Label(root, text="Blue Sky", bg="blue", fg="white")
w.pack(fill=X,pady=10)
mainloop()
Pack() method
ipadx Internal padding, horizontally.
from Tkinter import *
root = Tk()
w = Label(root, text="Red Sun", bg="red", fg="white")
w.pack()
w = Label(root, text="Green Grass", bg="green", fg="black")
w.pack(ipadx=10)
w = Label(root, text="Blue Sky", bg="blue", fg="white")
w.pack()
mainloop()
Pack() method
ipady Internal padding, vertically
from Tkinter import *
root = Tk()
w = Label(root, text="Red Sun", bg="red", fg="white")
w.pack()
w = Label(root, text="Green Grass", bg="green", fg="black")
w.pack(ipadx=10)
w = Label(root, text="Blue Sky", bg="blue", fg="white")
w.pack(ipady=10)
mainloop()
The default value in all cases is 0.
Pack() method
Placing widgets side by side
from Tkinter import *
root = Tk()
w = Label(root, text="red", bg="red", fg="white")
w.pack(padx=5, pady=10, side=LEFT)
w = Label(root, text="green", bg="green", fg="black")
w.pack(padx=5, pady=20, side=LEFT)
w = Label(root, text="blue", bg="blue", fg="white")
w.pack(padx=5, pady=20, side=LEFT)
mainloop()
Place() method
This geometry manager organizes widgets by placing them in a
specific position in the parent widget.
Syntax:
widget.place( place_options )
Here is the list of possible options −
anchor − The exact spot of widget other options refer to: may be N,
E, S, W, NE, NW, SE, or SW, compass directions indicating the
corners and sides of widget; default is NW (the upper left corner of
widget)
bordermode − INSIDE (the default) to indicate that other options
refer to the parent's inside (ignoring the parent's border); OUTSIDE
otherwise.
Place() method
height, width − Height and width in pixels.
relheight, relwidth − Height and width as a float between 0.0 and
1.0, as a fraction of the height and width of the parent widget.
relx, rely − Horizontal and vertical offset as a float between 0.0 and
1.0, as a fraction of the height and width of the parent widget.
x, y − Horizontal and vertical offset in pixels.
Place() method
Example
from tkinter import *
from tkinter import messagebox
top = Tk()
def helloCallBack():
messagebox.showinfo("Say Hello", "Hello World")
B = Button(top, text ="Hello", command = helloCallBack)
B.place(x = 35,y = 50)
top.mainloop()
Grid manager
The first geometry manager of Tk had been pack.
The algorithmic behaviour of pack is not easy to understand and it
can be difficult to change an existing design.
Grid was introduced in 1996 as an alternative to pack.
Though grid is easier to learn and to use and produces nicer
layouts, lots of developers keep using pack.
Grid is in many cases the best choice for general use.
While pack is sometimes not sufficient for changing details in the
layout, place gives you complete control of positioning each
element, but this makes it a lot more complex than pack and grid.
Grid manager
The Grid geometry manager places the widgets in a 2-dimensional
table, which consists of a number of rows and columns.
The position of a widget is defined by a row and a column number.
Widgets with the same column number and different row numbers will
be above or below each other.
Correspondingly, widgets with the same row number but different
column numbers will be on the same "line" and will be beside of each
other, i.e. to the left or the right.
Using the grid manager means that you create a widget, and use the
grid method to tell the manager in which row and column to place them.
The size of the grid doesn't have to be defined, because the manager
automatically determines the best dimensions for the widgets used.
Grid manager
from Tkinter import *
colours = ['red','green','orange','white','yellow','blue']
r=0
for c in colours:
Label(text=c, relief=RIDGE,width=15).grid(row=r,column=0)
Entry(bg=c, relief=SUNKEN,width=10).grid(row=r,column=1)
r=r+1
mainloop()
Tkinter Variable Classes
Variables can be used with most entry widgets to track changes to the
entered value.
The Checkbutton and Radiobutton widgets require variables to work
properly.
Some widgets (like text entry widgets, radio buttons and so on) can be
connected directly to application variables by using special options:
variable, textvariable, onvalue, offvalue, and value.
Create a Tkinter variable:
x = StringVar() # Holds a string; default value ""
x = IntVar() # Holds an integer; default value 0
x = DoubleVar() # Holds a float; default value 0.0
x = BooleanVar() # Holds a boolean, returns 0 for False and 1 for True
Example:
var = StringVar()
var.set("hello") #to set the value, call the set method
Tkinter Widgets
Tkinter provides various controls, such as buttons, labels and text boxes
used in a GUI application.
These controls are commonly called widgets.
Label
Button
tk_optoinMenu
Canvas
progress-bar
combo-box
radio button
frame
scroll bar
level
Separator
check-button
tree-view and many more...
entry
level-frame
menu
list – box
menu button
message
Tkinter Widgets - Label
Label: A label is a widget that displays text or images, typically that the
user will just view does not interact with. Labels are used for such things
as identifying controls or other parts of the user interface, providing
textual feedback or results, etc.
Syntax:
w = Label ( master, option, ... )
master − represents the parent window.
options − list of commonly used options for this widget.
Tkinter Widgets - Label
Tkinter Widgets - Button
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
Syntax:
w = Button ( master, option=value, ... )
master − represents the parent window.
options − list of commonly used options for this widget.
Tkinter Widgets - Button
Tkinter Widgets - Button
Tkinter Widgets - CheckButton
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.
Checkboxes are shown on the screen as square boxes.
A Checkbox has two states: on or off.
Syntax:
w = Checkbutton ( master, option, ... )
master − represents the parent window.
options − list of commonly used options for this widget.
Tkinter Widgets – Radio Button
Radiobutton:
A radio button, sometimes called option button, is a graphical user
interface element of Tkinter, which allows the user to choose (exactly) one
of a predefined set of options.
Syntax:
w = Radiobutton ( master, option, ... )
master − represents the parent window.
options − list of commonly used options for this widget.
Tkinter Widgets – Entry
Entry:
The Entry widget is used to accept single-line text strings from a user.
Entry widgets are the basic widgets of Tkinter used to get input, i.e. text
strings, from the user of an application.
Syntax: w = Entry( master, option, ... )
master − represents the parent window.
options − list of commonly used options for this widget.
Tkinter Widgets – Text
Text: A text widget is used for multi-line text area.
The Text widget provides formatted text display. It allows you to display
and edit text with various styles and attributes. It allows user to edit a
multiline text and format the way it has to be displayed, such as changing
its color and font.
Syntax: w = Text( master, option, ... )
master − represents the parent window.
options − list of commonly used options for this widget.
Tkinter Widgets – Entry
Text: A text widget is used for multi-line text area.
Tags are used to associate names to regions of text which makes easy
the task of modifying the display settings of specific text areas.