Modern Tkinter Python For Developers - Xiaolu Hou
Modern Tkinter Python For Developers - Xiaolu Hou
George W New was received Bachelor of Computer Science from the American University, and
Bachelor of Business Administration from the American University, USA.
Table of Contents
Contents
About the Authors
Table of Contents
Modern Tkinter Python for Developers
PART 1: Introduction
CHAPTER 1: Introduction to Tkinter
What is Tkinter?
What are Widgets?
CHAPTER 2: What are Widgets in Tkinter?
Widgets
Widget Classes
Geometry Management
CHAPTER 3: Hello World in Tkinter
Creating the Hello World program in Tkinter
CHAPTER 4: Create First GUI Application using Python-Tkinter
Getting Started
Widgets
Geometry Management
CHAPTER 5: Python GUI – tkinter
PART 2: Widgets
CHAPTER 1: Creating a button in tkinter
CHAPTER 2: Add style to tkinter button
CHAPTER 3: Add image on a Tkinter button
CHAPTER 4: Python Tkinter – Label
Label Widget
Python3
CHAPTER 5: Create LabelFrame and add widgets to it
RadioButton in Tkinter
CHAPTER 6: Python Tkinter – Checkbutton Widget
Checkbutton Widget
CHAPTER 7: Python Tkinter – Canvas Widget
Canvas widget
Some common drawing methods:
CHAPTER 8: Create different shapes using Canvas class
CHAPTER 9: Create different type of lines using Canvas class
CHAPTER 10: Moving objects using Canvas.move() method
Python3
CHAPTER 11: Combobox Widget in tkinter
CHAPTER 12: maxsize() method in Tkinter
Python3
Python3
CHAPTER 13: minsize() method in Tkinter
CHAPTER 14: resizable() method in Tkinter
CHAPTER 15: Python Tkinter – Entry Widget
The Entry Widget
CHAPTER 16: Tkinter – Read only Entry Widget
CHAPTER 17: Python Tkinter – Text Widget
Text Widget
Python3
Python3
CHAPTER 18: Python Tkinter – Message
Message widget
CHAPTER 19: Menu widget in Tkinter
CHAPTER 20: Python Tkinter – Menubutton Widget
Menubutton widget
CHAPTER 21: Python Tkinter – SpinBox
Spinbox widget
CHAPTER 22: Progressbar widget in Tkinter
CHAPTER 23: Python Tkinter - Scrollbar
Scrollbar Widget
CHAPTER 24: Python Tkinter – ScrolledText Widget
CHAPTER 25: Python Tkinter – ListBox Widget
ListBox widget
Python3
Python3
CHAPTER 26: Scrollable ListBox in Python-tkinter
Adding Scrollbar to ListBox
CHAPTER 27: Python Tkinter – Frame Widget
Frame
CHAPTER 28: Scrollable Frames in Tkinter
CHAPTER 29: Make a proper double scrollbar frame in Tkinter
CHAPTER 30: Python Tkinter – Scale Widget
Scale widget
CHAPTER 31: Hierarchical treeview in Python GUI application
Treeview widgets
CHAPTER 32: Tkinter Treeview scrollbar
Treeview scrollbar
PART 3: Toplevel Widgets
CHAPTER 1: Python Tkinter – Toplevel Widget
Toplevel widget
CHAPTER 2: askopenfile() function in Tkinter
CHAPTER 3: asksaveasfile() function in Tkinter
CHAPTER 4: Tkinter askquestion Dialog
Askquestion()
CHAPTER 5: Python Tkinter – MessageBox Widget
MessageBox Widget
CHAPTER 6: Create a Yes/No Message Box in Python using tkinter
CHAPTER 7: Change the size of MessageBox – Tkinter
CHAPTER 8: Different messages in Tkinter
CHAPTER 9: Change Icon for Tkinter MessageBox
Default icon of MessageBox
CHAPTER 10: Tkinter Choose color Dialog
Creating choose color dialog box using Tkinter
askcolor()
CHAPTER 11: Popup Menu in Tkinter
PART 4: Geometry Management====
CHAPTER 1: place() method in Tkinter
Python3
Python3
CHAPTER 2: grid() method in Tkinter
CHAPTER 3: grid_location() and grid_size() method
grid_location() method –
grid_size() method –
pack() method in Tkinter
CHAPTER 4: forget_pack() and forget_grid() method in Tkinter
forget_pack() method –
forget_grid() method –
CHAPTER 5: PanedWindow Widget in Tkinter
CHAPTER 6: Geometry Method in Python Tkinter
Tkinter window without using geometry method.
Examples of Tkinter Geometry Method in Python
Using the geometry method to set the dimensions and positions of the Tkinter window.
CHAPTER 7: Setting the position of TKinter labels
PART 5: Binding Functions
CHAPTER 1: Binding function in Tkinter
Python3
Python3
Python3
CHAPTER 2: Binding Function with double click with Tkinter ListBox
CHAPTER 3: Right Click menu using Tkinter
CHAPTER 4: Reading Images With Python – Tkinter
Reading Images With Tkinter
CHAPTER 5: iconphoto() method in Tkinter
CHAPTER 6: Loading Images in Tkinter using PIL
PART 6: Applications and Projects
CHAPTER 1: Simple GUI calculator using Tkinter
CHAPTER 2: Create a stopwatch using python
CHAPTER 3: Real time currency converter using Tkinter
Python3
CHAPTER 4: Create Table Using Tkinter
Creating Tables Using Tkinter
CHAPTER 5: GUI Calendar using Tkinter
Python3
CHAPTER 6: File Explorer in Python using Tkinter
Conclusion
Modern Tkinter Python for
Developers
PART 1: Introduction
What is Tkinter?
Tkinter is the inbuilt python module that is used to create GUI applications.
It is one of the most commonly used modules for creating GUI applications
in Python as it is simple and easy to work with. You don’t need to worry
about the installation of the Tkinter module separately as it comes with
Python already. It gives an object-oriented interface to the Tk GUI toolkit.
Some other Python Libraries available for creating our own GUI applications
are
Kivy
Python Qt
wxPython
Example
PYTHON
root = Tk()
root.title("First_Program")
# Label is what output will be
root.mainloop()
Output
CHAPTER 2: What are Widgets in
Tkinter?
Widgets
In general, Widget is an element of Graphical User Interface (GUI) that
displays/illustrates information or gives a way for the user to interact with
the OS. In Tkinter , Widgets are objects ; instances of classes that represent
buttons, frames, and so on.
Each separate widget is a Python object. When creating a widget, you must
pass its parent as a parameter to the widget creation function. The only
exception is the “root” window, which is the top-level window that will
contain everything else and it does not have a parent.
Example :
Python
root = Tk()
# geometry method
frame.pack()
# inside root
button.pack()
root.mainloop()
Output :
Widget Classes
Tkinter supports the below mentioned core widgets –
Widgets Description
Label It is used to display text or image on the screen
Button It is used to add buttons to your application
It is used to draw pictures and others layouts like texts,
Canvas graphics etc.
It contains a down arrow to select from list of available
ComboBox options
Metho
d Description
pack(
The Pack geometry manager packs widgets in rows or columns.
)
Now we create a Label widget as a child to the root window. Here root is
the parent of our label widget. We set the default text to “Hello, World!”
Note: This gets displayed in the window. A Label widget can display
either text or an icon or other image.
a.pack()
Next, we call the pack() method on this widget. This tells it to size itself
to fit the given text, and make itself visible.It just tells the geometry
manager to put widgets in the same row or column. It’s usually the easiest
to use if you just want one or a few widgets to appear.
root.mainloop()
The application window does not appear before you enter the main loop.
This method says to take all the widgets and objects we created, render
them on our screen, and respond to any interactions. The program stays in
the loop until we close the window.
root = Tk()
a.pack()
root.mainloop()
Output:
There are a number of libraries that are similar to Tkinter and can be used for
creating graphical user interfaces (GUIs) in Python. Some examples include:
Getting Started
1. Import tkinter package and all of its modules.
2. Create a root window. Give the root window a title(using title()) and
dimension(using geometry()). All other widgets will be inside the root
window.
3. Use mainloop() to call the endless loop of the window. If you forget to
call this nothing will appear to the user. The window will wait for any user
interaction till we close it.
Example:
Python3
# Import Module
root = Tk()
root.title("Welcome to GeekForGeeks")
root.geometry('350x200')
# Execute Tkinter
root.mainloop()
Output:
Root Window
4. We’ll add a label using the Label Class and change its text configuration
as desired. The grid() function is a geometry manager which keeps the label
in the desired location inside the window. If no parameters are mentioned by
default it will place it in the empty cell; that is 0,0 as that is the first location.
Example:
Python3
# Import Module
root = Tk()
root.title("Welcome to GeekForGeeks")
# Set geometry(widthxheight)
root.geometry('350x200')
#adding a label to the root window
lbl.grid()
# Execute Tkinter
root.mainloop()
Output:
5. Now add a button to the root window. Changing the button configurations
gives us a lot of options. In this example we will make the button display a
text once it is clicked and also change the color of the text inside the button.
Example:
Python3
# Import Module
from tkinter import *
root = Tk()
root.title("Welcome to GeekForGeeks")
# Set geometry(widthxheight)
root.geometry('350x200')
lbl.grid()
# button is clicked
def clicked():
# inside
fg = "red", command=clicked)
# set Button grid
btn.grid(column=1, row=0)
# Execute Tkinter
root.mainloop()
Output:
Button added
6. Using the Entry() class we will create a text box for user input. To display
the user input text, we’ll make changes to the function clicked(). We can get
the user entered text using the get() function. When the Button after entering
of the text, a default text concatenated with the user text. Also change button
grid location to column 2 as Entry() will be column 1.
Example:
Python3
# Import Module
root = Tk()
root.title("Welcome to GeekForGeeks")
# Set geometry(widthxheight)
root.geometry('350x200')
lbl.grid()
# button is clicked
def clicked():
lbl.configure(text = res)
fg = "red", command=clicked)
btn.grid(column=2, row=0)
# Execute Tkinter
root.mainloop()
Output:
Entry Widget at column 2 row 0
7. To add a menu bar, you can use Menu class. First, we create a menu, then
we add our first label, and finally, we assign the menu to our window. We
can add menu items under any menu by using add_cascade().
Example:
Python3
# Import Module
root = Tk()
root.title("Welcome to GeekForGeeks")
# Set geometry(widthxheight)
root.geometry('350x200')
menu = Menu(root)
item = Menu(menu)
item.add_command(label='New')
menu.add_cascade(label='File', menu=item)
root.config(menu=menu)
lbl.grid()
# button is clicked
def clicked():
lbl.configure(text = res)
fg = "red", command=clicked)
btn.grid(column=2, row=0)
# Execute Tkinter
root.mainloop()
Output :
Menu bar
This simple GUI covers the basics of Tkinter package. Similarly, you can add
more widgets and change their configurations as desired.
Widgets
Tkinter provides various controls, such as buttons, labels and text boxes used
in a GUI application. These controls are commonly called Widgets. The list
of commonly used Widgets are mentioned below –
S
N
Widget Description
o
.
Geometry Management
There are two main methods used which the user needs to remember while
creating the Python application with GUI.
1. Tk(screenName=None, baseName=None, className=’Tk’,
useTk=1): To create a main window, tkinter offers a method
‘Tk(screenName=None, baseName=None, className=’Tk’,
useTk=1)’. To change the name of the window, you can change the
className to the desired one. The basic code used to create the main
window of the application is:
m.mainloop()
Python
import tkinter
m = tkinter.Tk()
'''
'''
m.mainloop()
There are a number of widgets which you can put in your tkinter application.
Some of the major widgets are explained below:
1. Button:To add a button in your application, this widget is used. The
general syntax is:
w=Button(master, option=value)
master is the parameter used to represent the parent window. There are
number of options which are used to change the format of the Buttons.
Number of options can be passed as parameters separated by commas.
Some of them are listed below.
activebackground: to set the background color when button is
under the cursor.
Python
import tkinter as tk
r = tk.Tk()
r.title('Counting Seconds')
button.pack()
r.mainloop()
Output:
w = Canvas(master, option=value)
There are number of options which are used to change the format of the
widget. Number of options can be passed as parameters separated by
commas. Some of them are listed below.
Python
master = Tk()
w.pack()
canvas_height=20
canvas_width=200
y = int(canvas_height / 2)
w.create_line(0, y, canvas_width, y )
mainloop()
Output:
There are number of options which are used to change the format of this
widget. Number of options can be passed as parameters separated by
commas. Some of them are listed below.
Python
master = Tk()
var1 = IntVar()
var2 = IntVar()
mainloop()
Output:
Entry:It is used to input the single line text entry from the user.. For
multi-line text input, Text widget is used. The general syntax is:
w=Entry(master, option=value)
master is the parameter used to represent the parent window. There are
number of options which are used to change the format of the widget.
Number of options can be passed as parameters separated by commas.
Some of them are listed below.
bd: to set the border width in pixels.
Python
master = Tk()
e2 = Entry(master)
e1.grid(row=0, column=1)
e2.grid(row=1, column=1)
mainloop()
Output:
Frame: It acts as a container to hold the widgets. It is used for
grouping and organizing the widgets. The general syntax is:
w = Frame(master, option=value)
There are number of options which are used to change the format of the
widget. Number of options can be passed as parameters separated by
commas. Some of them are listed below.
root = Tk()
frame = Frame(root)
frame.pack()
bottomframe = Frame(root)
root.mainloop()
Output:
Label: It refers to the display box where you can put any text or
image which can be updated any time as per the code. The general syntax
is:
w=Label(master, option=value)
There are number of options which are used to change the format of the
widget. Number of options can be passed as parameters separated by
commas. Some of them are listed below.
bg: to set the normal background color.
Python
root = Tk()
w = Label(root, text='GeeksForGeeks.org!')
w.pack()
root.mainloop()
Output:
Listbox: It offers a list to the user from which the user can accept any
number of options. The general syntax is:
w = Listbox(master, option=value)
There are number of options which are used to change the format of the
widget. Number of options can be passed as parameters separated by
commas. Some of them are listed below.
highlightcolor: To set the color of the focus highlight when
widget has to be focused.
Python
top = Tk()
Lb = Listbox(top)
Lb.insert(1, 'Python')
Lb.insert(2, 'Java')
Lb.insert(3, 'C++')
Lb.pack()
top.mainloop()
Output:
There are number of options which are used to change the format of the
widget. Number of options can be passed as parameters separated by
commas. Some of them are listed below.
activebackground: To set the background when mouse is over the
widget.
Python
top = Tk()
mb.grid()
mb["menu"] = mb.menu
cVar = IntVar()
aVar = IntVar()
mb.pack()
top.mainloop()
Output:
There are number of options which are used to change the format of this
widget. Number of options can be passed as parameters separated by
commas. Some of them are listed below.
title: To set the title of the widget.
Python
from tkinter import *
root = Tk()
menu = Menu(root)
root.config(menu=menu)
filemenu = Menu(menu)
menu.add_cascade(label='File', menu=filemenu)
filemenu.add_command(label='New')
filemenu.add_command(label='Open...')
filemenu.add_separator()
filemenu.add_command(label='Exit', command=root.quit)
helpmenu = Menu(menu)
menu.add_cascade(label='Help', menu=helpmenu)
helpmenu.add_command(label='About')
mainloop()
Output:
There are number of options which are used to change the format of the
widget. Number of options can be passed as parameters separated by
commas. Some of them are listed below.
bd: to set the border around the indicator.
Python
from tkinter import *
main = Tk()
messageVar.config(bg='lightgreen')
messageVar.pack( )
main.mainloop( )
Output:
w = RadioButton(master, option=value)
There are number of options which are used to change the format of this
widget. Number of options can be passed as parameters separated by
commas. Some of them are listed below.
activebackground: to set the background color when widget is
under the cursor.
Python
root = Tk()
v = IntVar()
mainloop()
Output:
There are number of options which are used to change the format of the
widget. Number of options can be passed as parameters separated by
commas. Some of them are listed below.
cursor: To change the cursor pattern when the mouse is over the
widget.
to: To set the value of the other end of the scale range.
Python
master = Tk()
w.pack()
w.pack()
mainloop()
Output:
There are number of options which are used to change the format of the
widget. Number of options can be passed as parameters separated by
commas. Some of them are listed below.
width: to set the width of the widget.
Python
root = Tk()
scrollbar = Scrollbar(root)
mainloop()
Output:
There are number of options which are used to change the format of the
text. Number of options can be passed as parameters separated by
commas. Some of them are listed below.
highlightcolor: To set the color of the focus highlight when
widget has to be focused.
Python
root = Tk()
T.pack()
mainloop()
Output:
There are number of options which are used to change the format of the
widget. Number of options can be passed as parameters separated by
commas. Some of them are listed below.
bg: to set the normal background color.
bd: to set the size of border around the indicator.
Python
root = Tk()
root.title('GfG')
top = Toplevel()
top.title('Python')
top.mainloop()
Output:
SpinBox: It is an entry of ‘Entry’ widget. Here, value can be input by
selecting a fixed value of numbers.The general syntax is:
w = SpinBox(master, option=value)
There are number of options which are used to change the format of the
widget. Number of options can be passed as parameters separated by
commas. Some of them are listed below.
bg: to set the normal background color.
Python
master = Tk()
w.pack()
mainloop()
Output:
master is the parameter used to represent the parent window. There are
number of options which are used to change the format of the widget.
Number of options can be passed as parameters separated by commas.
Some of them are listed below.
bg: to set the normal background color.
Python
m1 = PanedWindow()
left = Entry(m1, bd = 5)
m1.add(left)
m2 = PanedWindow(m1, orient = VERTICAL)
m1.add(m2)
m2.add(top)
mainloop()
Output:
PART 2: Widgets
Python3
root = Tk()
root.geometry('100x100')
# Create a Button
command = root.destroy)
btn.pack(side = 'top')
root.mainloop()
Output:
Creation of Button using tk themed widget (tkinter.ttk). This will give you
the effects of modern graphics. Effects will change from one OS to another
because it is basically for the appearance.
Code #2:
Python3
# Create Object
root = Tk()
root.geometry('100x100')
command = root.destroy)
btn.pack(side = 'top')
root.mainloop()
Output:
Note: See in the Output of both the code, BORDER is not present in 2nd
output because tkinter.ttk does not support border. Also, when you hover the
mouse over both the buttons ttk.Button will change its color and become
light blue (effects may change from one OS to another) because it supports
modern graphics while in the case of a simple Button it won’t change color
as it does not support modern graphics.
CHAPTER 2: Add style to tkinter button
Tkinter is a Python standard library that is used to create GUI (Graphical
User Interface) applications. It is one of the most commonly used packages
of Python. Tkinter supports both traditional and modern graphics support
with the help of Tk themed widgets. All the widgets that Tkinter also has
available in tkinter.ttk.
Adding style in a tkinter.ttk button is a little creepy because it doesn’t support
direct implementation. To add styling in a ttk.Button we have to first create
an object of style class which is available in tkinter.ttk.
ttk.Button options –
command: A function to be called when button is pressed.
text: Text which appears on the Button.
image: Image to be appeared on the Button.
style: Style to be used in rendering this button.
To add styling on the ttk.Button we cannot directly pass the value in the
options. Firstly, we have to create a Style object which can be created as
follows:
style = ttk.Style()
Below code will be adding style to only selected Buttons i.e, only those
buttons will get changed in which we will be passing style option.
Code #1:
Python3
# Create Object
root = Tk()
root.geometry('100x100')
style = Style()
style.configure('W.TButton', font =
foreground = 'red')
style = 'W.TButton',
command = root.destroy)
btn1.grid(row = 0, column = 3, padx = 100)
# Execute Tkinter
root.mainloop()
Output:
Only one button will get styled because in the above code we are providing
styling only in one Button.
Python3
root = Tk()
# Set Geometry(widthxheight)
root.geometry('100x100')
style = Style()
style.configure('TButton', font =
foreground = 'red')
# button 1
style = 'TButton',
command = root.destroy)
# button 2
# Execute Tkinter
root.mainloop()
Output:
Now if you want to change the appearance of the buttons by the movement
of the mouse i.e, now when we hover the mouse over the button it will
change its color when we press it will change color, and so on.
Python3
root = Tk()
# Set Geometry(widthxheight)
root.geometry('500x500')
# Create style Object
style = Style()
style.configure('TButton', font =
borderwidth = '4')
# button 1
# button 2
# Execute Tkinter
root.mainloop()
Output:
Syntax:
photo = PhotoImage(file = "path_of_file")
Code #1:
root = Tk()
mainloop()
Output:
In output observe that only image is shown on the button and the size of the
button is also bigger than the usual size it is because we haven’t set the size
of the image.
root = Tk()
photoimage = photo.subsample(3, 3)
mainloop()
Output:
Observe that both text and image are appearing as well as size of the image is
also small.
CHAPTER 4: Python Tkinter – Label
Python offers multiple options for developing a GUI (Graphical User
Interface). Out of all the GUI methods, Tkinter is the most commonly used
method. It is a standard Python interface to the Tk GUI toolkit shipped with
Python. Python with Tkinter is the fastest and easiest way to create GUI
applications. Creating a GUI using Tkinter is an easy task using widgets.
Widgets are standard graphical user interfaces (GUI) elements, like buttons
and menus. Note: For more information, refer to Python GUI – tkinter
Label Widget
Tkinter Label is a widget that is used to implement display boxes where you
can place text or images. The text displayed by this widget can be changed
by the developer at any time you want. It is also used to perform tasks such
as to underline the part of the text and span the text across multiple lines. It is
important to note that a label can use only one font at a time to display text.
To use a label, you just have to specify what to display in it (this can be text,
a bitmap, or an image). Syntax:
w = Label ( master, option, … )
Parameters:
Example:
Python3
top.geometry("450x300")
user_name = Label(top,
y = 60)
user_password = Label(top,
y = 100)
submit_button = Button(top,
y = 130)
user_name_input_area = Entry(top,
y = 60)
user_password_entry_area = Entry(top,
top.mainloop()
Output :
Python3
root = Tk()
root.geometry('250x150')
label_frame.pack(expand='yes', fill='both')
label1.place(x=0, y=5)
label2.place(x=0, y=35)
label3 = Label(label_frame,
label3.place(x=0, y=65)
# mouse) to terminate
mainloop()
Output:
Code
#2: Adding Button and CheckButton widgets inside LabelFrame.
Python3
root = Tk()
root.geometry('250x150')
label_frame.pack(expand='yes', fill='both')
# Buttons
btn1.place(x=30, y=10)
btn2.place(x=130, y=10)
# Checkbuttons
chkbtn1.place(x=30, y=50)
chkbtn2.place(x=30, y=80)
# mouse) to terminate
mainloop()
Output:
Note: One can also add another LabelFrame inside another LabelFrame, as
well as one can do styling of any LabelFrame like we do the styling of other
widgets.
RadioButton in Tkinter
The Radiobutton is a standard Tkinter widget used to implement one-of-
many selections. Radiobuttons can contain text or images, and you can
associate a Python function or method with each button. When the button is
pressed, Tkinter automatically calls that function or method.
Syntax:
Code #1:
Radio buttons, but not in the form of buttons, in form of button box. In order
to display button box, indicatoron/indicator option should be set to 0.
Python3
master = Tk()
master.geometry("175x175")
v = StringVar(master, "1")
mainloop()
Output:
00:10
The background of these button boxes is light blue. Button boxes having a
white backgrounds as well as sunken are selected ones.
Code #2: Changing button boxes into standard radio buttons. For this
remove indicatoron option.
Python3
master = Tk()
master.geometry("175x175")
v = StringVar(master, "1")
mainloop()
Output:
Code #3: Adding Style to Radio Button using style class.
Python3
master = Tk()
master.geometry('175x175')
v = StringVar(master, "1")
style = Style(master)
mainloop()
Output:
You may observe that font style is changed as well as background and
foreground colors are also changed. Here, TRadiobutton is used in style
class, it automatically applies styling to all the available Radiobuttons.
Checkbutton Widget
The Checkbutton widget is a standard Tkinter widget that is used to
implement on/off selections. Checkbuttons can contain text or images. When
the button is pressed, Tkinter calls that function or method.
Syntax:
The syntax to use the checkbutton is given below.
w = Checkbutton ( master, options)
Parameters:
Following are commonly used Option can be used with this widget :-
Methods:
Methods used in this widgets are as follows:
Example:
from tkinter import *
root = Tk()
root.geometry("300x200")
w.pack()
Checkbutton1 = IntVar()
Checkbutton2 = IntVar()
Checkbutton3 = IntVar()
variable = Checkbutton1,
onvalue = 1,
offvalue = 0,
height = 2,
width = 10)
variable = Checkbutton2,
onvalue = 1,
offvalue = 0,
height = 2,
width = 10)
variable = Checkbutton3,
onvalue = 1,
offvalue = 0,
height = 2,
width = 10)
Button1.pack()
Button2.pack()
Button3.pack()
mainloop()
Output:
CHAPTER 7: Python Tkinter – Canvas
Widget
Tkinter is a GUI toolkit used in python to make user-friendly GUIs.Tkinter is
the most commonly used and the most basic GUI framework available in
python. Tkinter uses an object-oriented approach to make GUIs.
Note: For more information, refer to Python GUI – tkinter
Canvas widget
The Canvas widget lets us display various graphics on the application. It can
be used to draw simple shapes to complicated graphs. We can also display
various kinds of custom widgets according to our needs.
Syntax:
C = Canvas(root, height, width, bd, bg, ..)
Optional parameters:
Creating an arc
Creating a Line
Creating a polygon
Python3
from tkinter import *
root = Tk()
C = Canvas(root, bg="yellow",
height=250, width=300)
320, 40,
fill="green")
210, start=0,
extent=220,
fill="red")
150,
fill="blue")
C.pack()
mainloop()
Output:
Python3
root = Tk()
# Create Title
root.geometry("500x350")
# Co-ordinates.
# Colour
Colour = "#000fff000"
# click is enabled.
w.bind( "<B1-Motion>", paint )
# create label.
l.pack()
w.pack()
mainloop()
Output:
CHAPTER 8: Create different shapes
using Canvas class
In Tkinter, Canvas class is used to create different shapes with the help of
some functions which are defined under Canvas class. Any shape that
Canvas class creates requires a canvas, so before creating any shapes a
Canvas object is required and needs to be packed to the main window.
We are using a class to show the working of functions that helps to creates
different shapes.
Class parameters –
Python3
self.master = master
self.create()
def create(self):
self.canvas = Canvas(self.master)
width = 2)
# Creates an ellipse with horizontal diameter
width = 2)
width = 2)
# Creates a polygon
master = Tk()
shape = Shape(master)
master.title("Shapes")
mainloop()
Output:
CHAPTER 9: Create different type of
lines using Canvas class
Syntax:
Canvas.create_line(x1, y1, x2, y2, ...., options = ...)
Note: Minimum of 4 points are required to create a line, but you can also add
multiple points to create different drawings.
Class parameters:
Python3
class GFG:
self.master = master
self.create()
def create(self):
self.canvas = Canvas(self.master)
# This creates a line of length 200 (straight horizontal line)
# This pack the canvas to the main window and make it expandable
if __name__ == "__main__":
master = Tk()
geeks = GFG(master)
master.title("Lines")
# on the screen
master.mainloop()
Output:
Python3
root=Tk()
root.title("canvas line")
root.geometry("555x555")
our_canvas=Canvas(root,width=300,height=200,bg="white")
our_canvas.pack()
#creating rectangle
our_canvas.create_rectangle(50,150,250,50,fill="blue")
root.mainloop()
Output:
import tkinter as tk
class MoveCanvas(tk.Canvas):
super().__init__(*args, **kwargs)
self.dx = 0
self.dy = 0
self.box = self.create_rectangle(0, 0, 10, 10, fill="black")
self.dt = 25
self.tick()
def tick(self):
self.after(self.dt, self.tick)
self.dx = dx
self.dy = dy
if __name__ == "__main__":
root = tk.Tk()
root.geometry("300x300")
cvs = MoveCanvas(root)
cvs.pack(fill="both", expand=True)
ds = 3
root.bind("<KeyPress-Left>", lambda _: cvs.change_heading(-ds, 0))
root.mainloop()
import tkinter as tk
window = tk.Tk()
window.title('Combobox')
window.geometry('500x250')
# label
# Combobox creation
n = tk.StringVar()
' February',
' March',
' April',
' May',
' June',
' July',
' August',
' September',
' October',
' November',
' December')
monthchoosen.grid(column = 1, row = 5)
monthchoosen.current()
window.mainloop()
Output:
Example 2: Combobox with initial default values.
We can also set the initial default values in the Combobox widget as shown
in the below sample code.
import tkinter as tk
window = tk.Tk()
window.geometry('350x250')
# Label
n = tk.StringVar()
textvariable = n)
# Adding combobox drop down list
' February',
' March',
' April',
' May',
' June',
' July',
' August',
' September',
' October',
' November',
' December')
monthchoosen.current(1)
window.mainloop()
Output:
CHAPTER 12: maxsize() method in
Tkinter
This method is used to set the maximum size of the root window (maximum
size a window can be expanded). User will still be able to shrink the size of
the window to the minimum possible. Syntax :
master.maxsize(height, width)
Python3
root = Tk()
mainloop()
Output : Initial size of the window (maximum size of the window is not set)
Expanded size of the window (this window can be expanded till the size of
the screen because size is not fixed).
Code #2: Fixing maximum size of the root window
Python3
# importing only those functions
root = Tk()
root.maxsize(200, 200)
mainloop()
Output : Maximum expanded size of the window
Note: Tkinter also offers a minsize() method which is used to set the
minimum size of the window.
Python3
root = Tk()
mainloop()
Root window after shrunken down, see the window is completely shrunken
because it has no minimum geometry.
Code #2: Root window with minimum size.
Python3
root = Tk()
root.minsize(150, 100)
mainloop()
Window shrunken to it’s minimum size (one cannot shrunk it any further).
Arguments to be passed:
-> In resizable() method user can pass either positive integer or True, to make
the window resizable.
-> To make window non-resizable user can pass 0 or False.
root = Tk()
root.title('Resizable')
root.geometry('250x100')
root.resizable(True, True)
mainloop()
Output:
Initial size – You may observe that the part inside blue circle is enabled i.e
window is resizable and can be expanded. After resizing still the part inside
the blue is enabled so you can still change the size of the window.
Code #2: Restricting root window to change it’s size (fixed size window).
root = Tk()
root.title('Resizable')
root.geometry('250x100')
root.resizable(0, 0)
mainloop()
Output:
You may observe that the part inside the blue circle is disabled i.e size of the
window cannot be altered.
Python3
root = tk.Tk()
root.mainloop()
Output :
Syntax :
entry = tk.Entry(parent, options)
Parameters:
Example:
Python3
# login screen
import tkinter as tk
root=tk.Tk()
root.geometry("600x400")
name_var=tk.StringVar()
passw_var=tk.StringVar()
def submit():
name=name_var.get()
password=passw_var.get()
name_var.set("")
passw_var.set("")
# creating a label for
# method
name_label.grid(row=0,column=0)
name_entry.grid(row=0,column=1)
passw_label.grid(row=1,column=0)
passw_entry.grid(row=1,column=1)
sub_btn.grid(row=2,column=1)
root.mainloop()
Output :
CHAPTER 16: Tkinter – Read only Entry
Widget
Python has a number of frameworks to develop GUI applications like PyQT,
Kivy, Jython, WxPython, PyGUI, and Tkinter. Python tkinter module offers a
variety of options to develop GUI based applications. Tkinter is an open-
source and available under Python license. Tkinter provides the simplest and
fastest way to develop a GUI application. Tkinter supports different widgets
of which the Entry widget is used to accept input from the user. However,
there are cases when a certain text needs to be in a read-only format to
prevent alterations by the user. This can be achieved by the Entry widget and
the various options available under the Entry widget.
In this article, we shall see the use of Tkinter variables. Python variables can
be used Tkinter widgets but do not provide the flexibility as provided by
Tkinter variables. Tkinter variables have a unique feature called ‘tracing’ that
can be used to trace changes made to associated variables. This is useful to
track accidental changes made to a variable while working. The code below
demonstrates the creation of a read-only Entry widget using Tkinter.
1. Import tkinter module
import tkinter
root = Tk()
Explanation:
This method creates a blank parent window with close, maximize, and
minimize buttons on the top.
4. Creating Labels for the entry widgets and positioning the labels
in the parent widget
5. L1 = Label(root, text="User Name")
6. L1.grid(row=0, column=0)
7. L2 = Label(root, text="Password")
L2.grid(row=1, column=0)
options: The options available under the grid() method which can
be used to alter the position of a widget in the parent widget are
row, rowspan, column, columnspan, padx, pady, ipadx, ipady and
sticky.
Explanation:
The grid() method splits the parent window into rows and columns just
like a two dimensional table. Here grid() method specifies the position of
the Label widget on the parent window.
8. Creating a Tkinter variable for the Entry widget
mystr = StringVar()
Syntax: StringVar()
Parameter: The constructor takes no argument. To set the value, set()
method is used.
Explanation:
StringVar is one of the inbuilt variable classes in Tkinter. The default
value of StringVar() is an empty string “” .
9. Setting the string value
mystr.set('[email protected]')
Syntax: set(string)
Parameter:
10.
Creating Entry widget
Explanation:
This method creates a Entry widget on the parent widget. The Entry
widget ‘entry’ is in disabled state which implies that it is in read-only
mode and cannot be changed by the user. However, the Entry widget
‘passwd’ is in normal state and accepts input from user which can be
changed if required. The grid() method positions the entry widget in the
parent widget.
11.
Run the application
mainloop()
Syntax: mainloop()
Explanation:
import tkinter
root = Tk()
L1.grid(row=0,column=0)
L2 = Label(root, text="Password")
L2.grid(row=1,column=0)
mystr = StringVar()
mystr.set('[email protected]')
entry = Entry(textvariable=mystr,
state=DISABLED).grid(row=0,
column=1,
padx=10,
pady=10)
passwd = Entry().grid(row=1,column=1,
padx=10,pady=10)
mainloop()
Output
Text Widget
Text Widget is used where a user wants to insert multiline text fields. This
widget can be used for a variety of applications where the multiline text is
required such as messaging, sending information or displaying information
and many other tasks. We can insert media files such as images and links also
in the Textwidget.
Syntax:
Optional parameters
bg – background colour
fg – foreground colour
bd – border of widget.
Example 1:
Python3
import tkinter as tk
root = Tk()
root.geometry("250x170")
# Create label
command = root.destroy)
l.pack()
T.pack()
b1.pack()
b2.pack()
T.insert(tk.END, Fact)
tk.mainloop()
Output
Example 2: Saving Text and performing operations
Python3
root = Tk()
root.geometry("300x300")
def Take_input():
print(INPUT)
if(INPUT == "120"):
Output.insert(END, 'Correct')
else:
width = 25,
bg = "light yellow")
width = 25,
bg = "light cyan")
width = 20,
text ="Show",
command = lambda:Take_input())
l.pack()
inputtxt.pack()
Display.pack()
Output.pack()
mainloop()
Output
CHAPTER 18: Python Tkinter – Message
Message widget
The Message widget is used to show the message to the user regarding the
behavior of the python application. The message text contains more than one
line.
Syntax:
Parameters:
Options:
Following are commonly used Option can be used with this widget :-
anchor: This option is used to decide the exact position of the text
within the space .Its default value is CENTER.
bg: This option used to represent the normal background color.
bitmap: This option used to display a monochrome image.
bd: This option used to represent the size of the border and the
default value is 2 pixels.
cursor: By using this option, the mouse cursor will change to that
pattern when it is over type.
font: This option used to represent the font used for the text.
fg: This option used to represent the color used to render the text.
height: This option used to represent the number of lines of text on
the message.
image: This option used to display a graphic image on the widget.
justify: This option used to control how the text is justified:
CENTER, LEFT, or RIGHT.
padx: This option used to represent how much space to leave to the
left and right of the widget and text. It’s default value is 1 pixel.
pady: This option used to represent how much space to leave above
and below the widget. It’s default value is 1 pixel.
relief: The type of the border of the widget. It’s default value is set to
FLAT.
text: This option used use newlines (“\n”) to display multiple lines of
text.
variable: This option used to represents the associated variable that
tracks the state of the widget.
width: This option used to represents the width of the widget. and
also represented in the number of characters that are represented in
the form of texts.
wraplength: This option will be broken text into the number of
pieces.
Example:
root = Tk()
root.geometry("300x200")
w.pack()
msg = Message( root, text = "A computer science portal for geeks")
msg.pack()
root.mainloop()
Output:
root = Tk()
root.title('Menu Demonstration')
# Creating Menubar
menubar = Menu(root)
file.add_separator()
edit.add_separator()
help_.add_separator()
# display Menu
root.config(menu = menubar)
mainloop()
Output:
Note: In above application, commands are set to None but one may add
different commands to different labels to perform the required task.
CHAPTER 20: Python Tkinter –
Menubutton Widget
Python offers multiple options for developing GUI (Graphical User
Interface). Out of all the GUI methods, tkinter is the most commonly used
method. It is a standard Python interface to the Tk GUI toolkit shipped with
Python. Python with tkinter is the fastest and easiest way to create the GUI
applications. Creating a GUI using tkinter is an easy task.
Note: For more information, refer to Python GUI – tkinter
Menubutton widget
The Menubutton widget can be defined as the drop-down menu that is shown
to the user all the time. The Menubutton is used to implement various types
of menus in the python application.
Syntax:
w = Menubutton ( master, options )
Parameters:
Options:
Following are commonly used Option can be used with this widget :-
Example:
root = Tk()
root.geometry("300x200")
w.pack()
menubutton.menu = Menu(menubutton)
menubutton["menu"]= menubutton.menu
var1 = IntVar()
var2 = IntVar()
var3 = IntVar()
menubutton.menu.add_checkbutton(label = "Courses",
variable = var1)
menubutton.menu.add_checkbutton(label = "Students",
variable = var2)
menubutton.menu.add_checkbutton(label = "Careers",
variable = var3)
menubutton.pack()
root.mainloop()
Output:
Spinbox widget
The Spinbox widget is used to select from a fixed number of values. It is an
alternative Entry widget and provides the range of values to the user.
Syntax:
Parameters:
Options:
Following are commonly used Option can be used with this widget :-
Methods:
Methods used in this widgets are as follows:
Example:
root = Tk()
root.geometry("300x200")
w.pack()
sp.pack()
root.mainloop()
Output:
root = Tk()
def bar():
import time
progress['value'] = 20
root.update_idletasks()
time.sleep(1)
progress['value'] = 40
root.update_idletasks()
time.sleep(1)
progress['value'] = 50
root.update_idletasks()
time.sleep(1)
progress['value'] = 60
root.update_idletasks()
time.sleep(1)
progress['value'] = 80
root.update_idletasks()
time.sleep(1)
progress['value'] = 100
progress.pack(pady = 10)
# infinite loop
mainloop()
def bar():
import time
progress['value'] = 20
root.update_idletasks()
time.sleep(0.5)
progress['value'] = 40
root.update_idletasks()
time.sleep(0.5)
progress['value'] = 50
root.update_idletasks()
time.sleep(0.5)
progress['value'] = 60
root.update_idletasks()
time.sleep(0.5)
progress['value'] = 80
root.update_idletasks()
time.sleep(0.5)
progress['value'] = 100
root.update_idletasks()
time.sleep(0.5)
progress['value'] = 80
root.update_idletasks()
time.sleep(0.5)
progress['value'] = 60
root.update_idletasks()
time.sleep(0.5)
progress['value'] = 50
root.update_idletasks()
time.sleep(0.5)
progress['value'] = 40
root.update_idletasks()
time.sleep(0.5)
progress['value'] = 20
root.update_idletasks()
time.sleep(0.5)
progress['value'] = 0
progress.pack(pady = 10)
# infinite loop
mainloop()
Scrollbar Widget
The scrollbar widget is used to scroll down the content. We can also create
the horizontal scrollbars to the Entry widget.
Syntax:
The syntax to use the Scrollbar widget is given below.
w = Scrollbar(master, options)
Parameters:
Options:
Following are commonly used Option can be used with this widget :-
Methods:
Methods used in this widgets are as follows:
get(): This method is used to returns the two numbers a and b which
represents the current position of the scrollbar.
set(first, last): This method is used to connect the scrollbar to the
other widget w. The yscrollcommand or xscrollcommand of the other
widget to this method.
Example:
root = Tk()
root.geometry("150x200")
font = "50")
w.pack()
scroll_bar = Scrollbar(root)
fill = Y )
mylist = Listbox(root,
yscrollcommand = scroll_bar.set )
root.mainloop()
Output:
Tkinter is a built-in standard python library. With the help of Tkinter, many
GUI applications can be created easily. There are various types of widgets
available in Tkinter such as button, frame, label, menu, scrolledtext, canvas
and many more. A widget is an element that provides various controls.
ScrolledText widget is a text widget with a scroll bar. The
tkinter.scrolledtext module provides the text widget along with a scroll bar. This
widget helps the user enter multiple lines of text with convenience. Instead of
adding a Scroll bar to a text widget, we can make use of a scrolledtext widget
that helps to enter any number of lines of text.
Example 1 : Python code displaying scrolledText widget.
win = tk.Tk()
win.title("ScrolledText Widget")
# Title Label
ttk.Label(win,
background = 'green',
foreground = "white").grid(column = 0,
row = 0)
# area widget
text_area = scrolledtext.ScrolledText(win,
wrap = tk.WORD,
width = 40,
height = 10,
text_area.focus()
win.mainloop()
Output :
import tkinter as tk
import tkinter.scrolledtext as st
# Creating tkinter window
win = tk.Tk()
win.title("ScrolledText Widget")
# Title Label
tk.Label(win,
background = 'green',
foreground = "white").grid(column = 0,
row = 0)
text_area = st.ScrolledText(win,
width = 30,
height = 8,
15))
"""\
Hi
Geeks !!!
Geeks !!!
Geeks !!!
Geeks !!!
Geeks !!!
Geeks !!!
Geeks !!!
""")
text_area.configure(state ='disabled')
win.mainloop()
Output :
In the first example, as you can see the cursor, the user can enter any number
of lines of text. In the second example, the user can just read the text which
is displayed in the text box and cannot edit/enter any lines of text. We may
observe that the scroll bar disappears automatically if the text entered by the
user is less than the size of the widget.
ListBox widget
The ListBox widget is used to display different types of items. These items
must be of the same type of font and having the same font color. The items
must also be of Text type. The user can select one or more items from the
given list according to the requirement.
Syntax:
listbox = Listbox(root, bg, fg, bd, height, width, font, ..)
Optional parameters
Common methods
Example 1:
Python3
top = Tk()
width = 15,
bg = "grey",
activestyle = 'dotbox',
font = "Helvetica",
fg = "yellow")
top.geometry("300x250")
listbox.insert(1, "Nachos")
listbox.insert(2, "Sandwich")
listbox.insert(3, "Burger")
listbox.insert(4, "Pizza")
listbox.insert(5, "Burrito")
label.pack()
listbox.pack()
# exits themselves.
top.mainloop()
Output:
Example 2: Let’s Delete the elements from the above created listbox
Python3
# Delete Items from the list
listbox.delete(2)
Output:
CHAPTER 26: Scrollable ListBox in
Python-tkinter
Tkinter is the standard GUI library for Python. Tkinter in Python comes with
a lot of good widgets. Widgets are standard GUI elements, and the Listbox,
Scrollbar will also come under this Widgets.
Note: For more information, refer to Python GUI – tkinter
Listbox
The ListBox widget is used to display different types of items. These items
must be of the same type of font and having the same font color. The items
must also be of Text type. The user can select one or more items from the
given list according to the requirement.
Syntax:
listbox = Listbox(root, bg, fg, bd, height, width, font, ..)
Scrollbar
The scrollbar widget is used to scroll down the content. We can also create
the horizontal scrollbars to the Entry widget.
Syntax:
The syntax to use the Scrollbar widget is given below.
w = Scrollbar(master, options)
Parameters:
root = Tk()
listbox = Listbox(root)
scrollbar = Scrollbar(root)
listbox.insert(END, values)
listbox.config(yscrollcommand = scrollbar.set)
# setting scrollbar command parameter
scrollbar.config(command = listbox.yview)
root.mainloop()
Output
CHAPTER 27: Python Tkinter – Frame
Widget
Python offers multiple options for developing GUI (Graphical User
Interface). Out of all the GUI methods, tkinter is the most commonly used
method. It is a standard Python interface to the Tk GUI toolkit shipped with
Python. Python with tkinter is the fastest and easiest way to create the GUI
applications. Creating a GUI using tkinter is an easy task.
Note: For more information, refer to Python GUI – tkinter
Frame
A frame is a rectangular region on the screen. A frame can also be used as a
foundation class to implement complex widgets. It is used to organize a
group of widgets.
Syntax:
Parameters:
Options:
Following are commonly used Option can be used with this widget :-
Example:
root.geometry("300x150")
w.pack()
frame = Frame(root)
frame.pack()
bottomframe = Frame(root)
root.mainloop()
Output:
CHAPTER 28: Scrollable Frames in
Tkinter
A scrollbar is a widget that is useful to scroll the text in another widget. For
example, the text in Text, Canvas Frame or Listbox can be scrolled from top
to bottom or left to right using scrollbars. There are two types of scrollbars.
They are horizontal and vertical. The horizontal scrollbar is useful to view
the text from left to right. The vertical scrollbar is useful to scroll the text
from top to bottom.
Now let us see how we can create a scrollbar. To create a scrollbar we have
to create a scrollbar class object as:
h = Scrollbar(root, orient='horizontal')
On attaching the scrollbar to a widget like text box, list box, etc we then have
to add a command xview for horizontal scrollbar and yview for the vertical
scrollbar.
Now let us look at the code for attaching a vertical and horizontal scrollbar to
a Text Widget.
Python3
# using Tkinter
from tkinter import *
class ScrollBar:
# constructor
def __init__(self):
root = Tk()
# the bootom
# to write orient as it is by
# default vertical
v = Scrollbar(root)
# the side
v.pack(side = RIGHT, fill = Y)
xscrollcommand = h.set,
yscrollcommand = v.set)
for i in range(20):
t.pack(side=TOP, fill=X)
# widget
h.config(command=t.xview)
# here command represents the method to
# widget
v.config(command=t.yview)
# click event
root.mainloop()
s = ScrollBar()
import tkinter as tk
window = tk.Tk()
window.geometry("250x200")
Output:
Functions to understand:
geometry(): This method is used to set the dimensions of the Tkinter
window as well as it is used to set the position of the main window
on the user’s desktop.
2) The next code is to assign to the scrollbars for horizontal and vertical.
SVBar = tk.Scrollbar(window)
fill = "y")
SHBar = tk.Scrollbar(window,
orient = tk.HORIZONTAL)
fill = "x")
Output:
Functions to understand:
Scrollbar() = It is the scrollbar that is allotted to the sides of the
window.
pack() method: It organizes the widgets in blocks before placing in
the parent widget.
TBox = tk.Text(window,
height = 500,
width = 500,
yscrollcommand = SVBar.set,
xscrollcommand = SHBar.set,
wrap = "none")
TBox = tk.Text(window,
height = 500,
width = 500,
yscrollcommand = SVBar.set,
xscrollcommand = SHBar.set,
wrap = "none")
SHBar.config(command = TBox.xview)
SVBar.config(command = TBox.yview)
Here, within the arguments of the function config(), the scrollbars are assigned
at their specific x-axis and y-axis and are able to function.
Now, insert some amount of text to display:
Num_Vertical =
(“\nA\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nL\nM\nN\nO\nP\nQ\nR\nS\nT\nU\
nV\nW\nX\nY\nZ”)
Num_Horizontal = (“A B C D E F G H I J K L M N O P Q R S T U V W X Y
Z”)
To insert the text in the window for the display, the following code is done:
TBox.insert(tk.END, Num_Horizontal)
TBox.insert(tk.END, Num_Vertical)
Complete Code:
import tkinter as tk
Num_Vertical = ("\nA\nB\nC\nD\nE\nF\nG\n\
H\nI\nJ\nK\nL\nM\nN\nO\nP\nQ\nR\nS\nT\n\
U\nV\nW\nX\nY\nZ")
Num_Horizontal = ("A B C D E F G H \
I J K L M N O P Q R S T U V\
W X Y Z")
window = tk.Tk()
window.geometry("250x200")
SVBar = tk.Scrollbar(window)
fill = "y")
SHBar = tk.Scrollbar(window,
orient = tk.HORIZONTAL)
fill = "x")
TBox = tk.Text(window,
height = 500,
width = 500,
yscrollcommand = SVBar.set,
xscrollcommand = SHBar.set,
wrap = "none")
TBox = tk.Text(window,
height = 500,
width = 500,
yscrollcommand = SVBar.set,
xscrollcommand = SHBar.set,
wrap = "none")
TBox.insert(tk.END, Num_Horizontal)
TBox.insert(tk.END, Num_Vertical)
SHBar.config(command = TBox.xview)
SVBar.config(command = TBox.yview)
window.mainloop()
Output:
CHAPTER 30: Python Tkinter – Scale
Widget
Tkinter is a GUI toolkit used in python to make user-friendly GUIs.Tkinter is
the most commonly used and the most basic GUI framework available in
python. Tkinter uses an object-oriented approach to make GUIs.
Note: For more information, refer to Python GUI – tkinter
Scale widget
The Scale widget is used whenever we want to select a specific value from a
range of values. It provides a sliding bar through which we can select the
values by sliding from left to right or top to bottom depending upon the
orientation of our sliding bar.
Syntax:
S = Scale(root, bg, fg, bd, command, orient, from_, to, ..)
Optional parameters
Methods
# scale widget
root = Tk()
root.geometry("400x300")
v1 = DoubleVar()
def show1():
from_ = 1, to = 100,
orient = HORIZONTAL)
command = show1,
bg = "yellow")
l1 = Label(root)
s1.pack(anchor = CENTER)
l3.pack()
b1.pack(anchor = CENTER)
l1.pack()
root.mainloop()
Output:
root = Tk()
root.geometry("400x300")
v2 = DoubleVar()
def show2():
from_ = 50, to = 1,
orient = VERTICAL)
command = show2,
bg = "purple",
fg = "white")
l2 = Label(root)
s2.pack(anchor = CENTER)
l4.pack()
b2.pack()
l2.pack()
root.mainloop()
Output:
Treeview widgets
This widget is helpful in visualizing and permitting navigation over a
hierarchy of items. It can display more than one feature of every item in the
hierarchy. It can build a tree view as a user interface like in Windows
explorer. Therefore, here we will use Tkinter in order to construct a
hierarchical treeview in the Python GUI application.
Let’s see an example of constructing a hierarchical treeview in Python GUI
application.
Example:
Python
# Importing tkinter
app = Tk()
treeview = ttk.Treeview(app)
# Inserting parent
text ='GeeksforGeeks')
# Inserting child
text ='Algorithm')
text ='Python')
treeview.insert('item4', 'end', 'Java',
text ='Java')
# Calling main()
app.mainloop()
Treeview scrollbar
When a scrollbar uses treeview widgets, then that type of scrollbar is called
as treeview scrollbar. Where, a treeview widget is helpful in displaying more
than one feature of every item listed in the tree to the right side of the tree in
the form of columns. However, it can be implemented using tkinter in python
with the help of some widgets and geometry management methods as
supported by tkinter.
Below example illustrates the usage of Treeview Scrollbar using Python-
tkinter:
Example 1:
Python
import tkinter as tk
window = tk.Tk()
window.resizable(width = 1, height = 1)
# with treeview
verscrlbar = ttk.Scrollbar(window,
orient ="vertical",
command = treev.yview)
# scrollbar
# Configuring treeview
treev.configure(xscrollcommand = verscrlbar.set)
# Defining heading
treev['show'] = 'headings'
# respective columns
# respective columns
# columns built
# Calling mainloop
window.mainloop()
PART 3: Toplevel Widgets
Toplevel widget
A Toplevel widget is used to create a window on top of all other windows.
The Toplevel widget is used to provide some extra information to the user
and also when our program deals with more than one application. These
windows are directly organized and managed by the Window Manager and
do not need to have any parent window associated with them every time.
Syntax:
toplevel = Toplevel(root, bg, fg, bd, height, width, font, ..)
Optional parameters
Common methods
Example 1:
Python3
root = Tk()
root.geometry("200x300")
root.title("main")
top = Toplevel()
top.geometry("180x100")
top.title("toplevel")
l2.pack()
top.mainloop()
Output
Python3
root = Tk()
root.title("Root Window")
root.geometry("450x300")
def open_Toplevel2():
# Create widget
top2 = Toplevel()
top2.title("Toplevel2")
# specify size
top2.geometry("200x100")
# Create label
label = Label(top2,
text = "This is a Toplevel2 window")
command = top2.destroy)
label.pack()
button.pack()
top2.mainloop()
def open_Toplevel1():
# Create widget
top1 = Toplevel(root)
top1.title("Toplevel1")
# specify size
top1.geometry("200x200")
# Create label
label = Label(top1,
command = top1.destroy)
command = open_Toplevel2)
label.pack()
button2.pack()
button1.pack()
top1.mainloop()
command = open_Toplevel1)
label1.pack()
root.mainloop()
Output
CHAPTER 2: askopenfile() function in
Tkinter
While working with GUI one may need to open files and read data from it or
may require to write data in that particular file. One can achieve this with the
help of open() function (python built-in) but one may not be able to select
any required file unless provides a path to that particular file in code.
With the help of GUI, you may not require to specify the path of any file but
you can directly open a file and read it’s content.
In order to use askopenfile() function you may require to follow these steps:
-> import tkinter -> from tkinter.filedialog import askopenfile ## Now you
can use this function -> file = askopenfile(mode=’r’, filetypes=[(‘any name
you want to display’, ‘extension of file type’)])
We have to specify the mode in which you want to open the file like in above
snippet, this will open a file in reading mode.
Python3
root.geometry('200x100')
# will be opened
def open_file():
content = file.read()
print(content)
mainloop()
Output:
Printed content of selected file –
Comparison of content of original file and printed content –
Note: In above code only .py (python files) types files will be open. To open
specified type of files, one has to mention it in the filetypes option along
with it’s extension as done in above code.
CHAPTER 3: asksaveasfile() function in
Tkinter
Python provides a variety of modules with the help of which one may
develop GUI (Graphical User Interface) applications. Tkinter is one of the
easiest and fastest way to develop GUI applications.
While working with files one may need to open files, do operations on files
and after that to save file. asksaveasfile() is the function which is used to save
user’s file (extension can be set explicitly or you can set default extensions
also). This function comes under the class filedialog.
Below is the Code:
root = Tk()
root.geometry('200x150')
def save():
files = [('All Files', '*.*'),
mainloop()
Output #1: Directory before saving any file (folder is initially empty)
Output #2: Dialogbox when user presses the save button (dialog box to save
file is opened). You may see in the output Python file as default is selected.
Output #3: Directory after saving 2 Python files (one may also change the
type of file)
Askquestion()
This function is used to ask questions to the user. That has only two options
YES or NO.
Application of this function:
1. We can use this to ask the user if the User want’s to continue.
2. We can use this to ask the user if the User wanted to Submit or not.
Syntax:
messagebox.askfunction((Title, Message, [, options])
Example:
Python3
# object of TK()
main = Tk()
# askquestion() function
def Submit():
messagebox.askquestion("Form",
# instance
main.geometry("100x100")
# creating Window
# Button positioning
B1.pack()
main.mainloop()
Output:
To use the GUI functionality in python we have to import the libraries. In the
first line, we are importing Tkinter, and second-line we’re importing
messagebox library
from tkinter import *
3. Set dimension
we set the dimension of the window we can set it in various ways.in this we
are setting is by geometry() function of size “100X100”.
top.geometry("100x100")
5. mainloop()
This method can be used when all the code is ready to execute.It runs the
INFINITE Loop used to run the application. A window will open until the
close button is pressed.
ICONS that We can use in Options
1. Error
2. Info
3. Warning
4. Question
We can change the icon of the dialog box. The type of icon that we want to
use just depends on the application’s need. we have four icons.
Error
messagebox.function_name(Title, Message, icon='error')
Example-
Python3
def check():
messagebox.askquestion("Form",
icon ='error')
main.geometry("100x100")
B1.pack()
main.mainloop()
Output:
info
messagebox.function_name(Title, Message, icon='info')
Example-
Python3
main = Tk()
def check():
messagebox.askquestion("Form",
icon ='info')
main.geometry("100x100")
B1.pack()
main.mainloop()
Output:
Question
messagebox.function_name(Title, Message, icon='question')
Example-
Python3
main = Tk()
def check():
messagebox.askquestion("Form",
icon ='question')
main.geometry("100x100")
B1 = Button(main, text = "check", command = check)
B1.pack()
main.mainloop()
Output:
Warning
messagebox.function_name(Title, Message, icon='warning')
Example-
Python3
main = Tk()
def check():
messagebox.askquestion("Form",
"Gender is empty?",
icon ='warning')
main.geometry("100x100")
B1.pack()
main.mainloop()
Output:
MessageBox Widget
Python Tkinter – MessageBox Widget is used to display the message boxes
in the python applications. This module is used to display a message using
provides a number of functions.
Syntax:
messagebox.Function_Name(title, message [, options])
Parameters:
Function_Name:
There are functions or methods available in the messagebox widget.
Example:
root = Tk()
root.geometry("300x200")
w.pack()
messagebox.showinfo("showinfo", "Information")
messagebox.showwarning("showwarning", "Warning")
messagebox.showerror("showerror", "Error")
root.mainloop()
Output:
CHAPTER 6: Create a Yes/No Message
Box in Python using tkinter
Python offers a number Graphical User Interface(GUI) framework but Tk
interface or tkinter is the most widely used framework. It is cross-platform
which allows the same code to be run irrespective of the OS platform
(Windows, Linux or macOS). Tkinter is lightweight, faster and simple to
work with. Tkinter provides a variety of widgets that can be customized
using standard attributes and geometry management methods. The Tkinter
message box can be used to ask questions or display messages to the user.
Note: For more information, refer to Python GUI – tkinter
Steps to create a tkinter message box :
Note: Name of the module in Python 2.x is ‘Tkinter’ and in Python 3.x it
is ‘tkinter’. Python 3.x is used here.
Explanation:
Syntax:
askquestion(title=None, message=None, **options)
Parameter
Parameter
Syntax:
destroy()
This method destroys a widget.
11.
Create the canvas for the button will be placed
12.
root=tk.Tk()
13.
canvas=tk.Canvas(root, width=200, height=200)
14.
canvas.pack()
Explanation:
Syntax:
Tk(screenName=None, baseName=None, className=’Tk’, useTk=1)
15.
Create the button and place it inside the canvas
16.
b=Button(root, text='Quit Application', command=call)
17.
canvas.create_window(100, 100, window=b)
Explanation:
Syntax:
Button(master=None, options)
Parameter:
Parameter:
18.
Call the mainloop() method
19.
root.mainloop()
Explanation:
Syntax:
mainloop()
import tkinter as tk
def call():
if res == 'yes' :
root.destroy()
else :
# Driver's code
root = tk.Tk()
canvas = tk.Canvas(root,
width = 200,
height = 200)
canvas.pack()
b = Button(root,
command = call)
canvas.create_window(100, 100,
window = b)
root.mainloop()
CHAPTER 7: Change the size of
MessageBox – Tkinter
Python have many libraries for GUI. Tkinter is one of the libraries that
provides a Graphical user interface. For the Short Message, we can use the
MessageBox Library. It has many functions for the effective interface. In this
MessageBox library provide different type of functions to Display Message
Box.
Example:
Python3
top = Tk()
def Button_1():
messagebox.showinfo("Status",
"Button-1 Pressed")
def Button_2():
messagebox.showinfo("Status",
"Button-2 Pressed")
top.geometry("100x100")
command = Button_1)
command = Button_2)
B1.pack()
B2.pack()
top.mainloop()
Output:
By default, the size of the message box is Fix. We can’t change the size of
that Message Box. Different Boxes have different sizes. However, we can
use Different alternative methods for this purpose
Message Widget
By Changing ReadMe File
1. Message Widget
Python3
main = Tk()
# Message Function
relief=RAISED )
label.pack()
main.mainloop()
Output:
top = Tk()
def helpfile(filetype):
if filetype==1:
with open("read.txt") as f:
# reading file
readme = f.read()
# Display whole message
messagebox.showinfo(title="Title",
message = str(readme))
# Driver code
helpfile(1)
top.mainloop()
Output:
CHAPTER 8: Different messages in
Tkinter
Tkinter provides a messagebox class which can be used to show variety of
messages so that user can respond according to those messages. Messages
like confirmation message, error message, warning message etc.
In order to use this class one must import this class as shown below:
# Ask a question.
print(askquestion("askquestion", "Question?"))
print(showerror("showerror", "Error"))
print(showinfo("showinfo", "Information"))
print(showwarning("showwarning", "Warning"))
Python3
import tkinter as tk
win = tk.Tk()
win.title("example")
win.mainloop()
Output :
In the above example, within the circle that is the default icon we get, when
it is not mentioned in the code. And yes, we can change it according to our
wishes. Select the photo you want to keep it as an icon. Select and then
[Right click–> Properties]. Type of File you see will be in the format of
(.png).
But we need it in the format of (.ico). There might be a question that why we
need to convert .png to .ico? Why can’t we use it in the format of .png? For
that, the answer will be the icon bitmap function (depending on the
programming language) should be used to set a bitmap image to the window
when the window is iconified. For that just search online for online
iconconverter, go there, and simply convert the image you want to convert it
to (.ico). So we got our image ready to the desired format, next get back to
the coding part and let’s learn how to change the default icon to our selected
icon follow the steps. Step 1: Add a line, defining the icon bitmap i.e.
win.iconbitmap(r”)
import tkinter as to
win = tk.Tk()
win.title("example")
win.iconbitmap(r'')
win.mainloop()
Step 2: Mentioning the file path of the image we want as an icon. Copy the
File location and paste it inside “win.iconbitmap(r”)”.
win.iconbitmap(r'C:\Users\Madhusudan\Downloads\')
Step 3: Mention the file name. Copy the file name and paste it after “\”
where you mentioned the file location.
win.iconbitmap(r'C:\Users\Madhusudan\Downloads\favicon(2).ico')
Finally, we get the complete code for how we can change the icon. Let’s put
it together.
Python3
import tkinter as tk
win = tk.Tk()
win.title("example")
win.iconbitmap(r'C:\Users\Madhusudan\Downloads\favicon(2).ico')
win.mainloop()
Output :
The process of importing the Tkinter module is the same as importing any
other module in Python.
import tkinter
askcolor()
This function belongs to the colorchooser package of Tkinter module. The
function helps in creating a color chooser dialog box. As soon as the function
is called, it makes the color chooser dialogue box pop up. The function
returns the hexadecimal code of the color selected by the user.
Syntax:
colorchooser.askcolor()
Example:
Python3
def choose_color():
print(color_code)
root = Tk()
command = choose_color)
button.pack()
root.geometry("300x300")
root.mainloop()
Output:
Note: The color chooser dialog box may vary for different operating
systems.
Popup menus are context menus that appear on user interaction. This menu
can be shown anywhere on the client window. below is the python code to
create a popup menu using Tkinter library.
import tkinter
class A:
def __init__(self):
self.root = tkinter.Tk()
self.root.geometry('500x500')
self.frame1 = tkinter.Label(self.root,
width = 400,
height = 400,
bg = '#AAAAAA')
self.frame1.pack()
#create menu
def popup(self):
self.popup_menu = tkinter.Menu(self.root,
tearoff = 0)
command = lambda:self.hey("hi"))
command = lambda:self.hey("hello"))
self.popup_menu.add_separator()
command = lambda:self.hey("bye"))
def do_popup(self,event):
try:
self.popup_menu.tk_popup(event.x_root,
event.y_root)
finally:
self.popup_menu.grab_release()
def hey(self,s):
self.frame1.configure(text = s)
def run(self):
self.popup()
self.root.bind("<Button-3>",self.do_popup)
tkinter.mainloop()
a = A()
a.run()
Functions
The Place geometry manager is the simplest of the three general geometry
managers provided in Tkinter. It allows you explicitly set the position and
size of a window, either in absolute terms, or relative to another window. You
can access the place manager through the place() method which is available
for all standard widgets. It is usually not a good idea to use place() for
ordinary window and dialog layouts; its simply too much work to get things
working as they should. Use the pack() or grid() managers for such
purposes. Syntax:
widget.place(relx = 0.5, rely = 0.5, anchor = CENTER)
Note : place() method can be used with grid() method as well as with pack()
method. Code #1:
Python3
# Importing tkinter module
# creating Tk window
master = Tk()
master.geometry("200x200")
# button widget
# label widget
l.place(anchor = NW)
# button widget
mainloop()
Output:
When we use pack() or grid() managers, then it is very easy to put two
different widgets separate to each other but putting one of them inside other
is a bit difficult. But this can easily be achieved by place() method.
In place() method, we can use in_ option to put one widget inside
other. Code #2:
Python3
# Importing tkinter module
# creating Tk window
master = Tk()
master.geometry("200x200")
# button widget
# button widget
# label widget
l.place(anchor = NW)
mainloop()
Output: In below images notice that one button is placed inside the other.
Creating this layout using the pack manager is possible, but it takes a
number of extra frame widgets, and a lot of work to make things look good.
If you use the grid manager instead, you only need one call per widget to get
everything laid out properly. Using the grid manager is easy. Just create the
widgets, and use the grid method to tell the manager in which row and
column to place them. You don’t have to specify the size of the grid
beforehand; the manager automatically determines that from the widgets in
it.
Code #1:
Python3
master = Tk()
e1 = Entry(master)
e2 = Entry(master)
# this will arrange entry widgets
# or mouse interrupt
mainloop()
Output:
Python3
master = Tk()
e1 = Entry(master)
e2 = Entry(master)
# checkbutton widget
img1 = img.subsample(2, 2)
mainloop()
Output:
Warning: Never mix grid() and pack() in the same master window.
grid_location() method –
This method returns a tuple containing (column, row) of any specified
widget. Since this method is a widget method you cannot use it with master
object ( or Tk() object). In order to use this method, you should first create a
Frame and treat it as a parent (or master).
Syntax: widget.grid_location(x, y)
Parameters:
x and y are the positions, relative to the upper left corner of the widget
(parent widget).
Python3
master = Tk()
# other widget
def click(event):
x = event.x_root - f.winfo_rootx()
y = event.y_root - f.winfo_rooty()
# parent widget
z = f.grid_location(x, y)
# printing position
print(z)
f = Frame(master)
f.pack()
# Button widgets
b.grid(row = 2, column = 3)
c = Button(f, text = "Button2")
c.grid(row = 1, column = 0)
master.bind("<Button-1>", click)
# infinite loop
mainloop()
grid_size() method –
This method is used to get the total number of grids present in any parent
widget. This is a widget method so one cannot use it with master object. One
has to create a Frame widget.
Python3
def grids(event):
# widget
x = f.grid_size()
print(x)
f = Frame(master)
f.pack()
# Button widgets
b.grid(row = 1, column = 2)
master.bind("<Button-1>", grids)
# infinite loop
mainloop()
Output:
Every time you click the mouse button it will return the same value until
more widgets are not added OR number of rows and columns are not
increased.
(3, 2)
The Pack geometry manager packs widgets relative to the earlier widget.
Tkinter literally packs all the widgets one after the other in a window. We
can use options like fill, expand, and side to control this geometry manager.
Compared to the grid manager, the pack manager is somewhat limited, but
it’s much easier to use in a few, but quite common situations:
Put a widget inside a frame (or any other container widget), and have
it fill the entire frame
Place a number of widgets on top of each other
Place a number of widgets side by side
Code #1: Putting a widget inside frame and filling entire frame. We can do
this with the help of expand and fill options.
Python3
# creating Tk window
master = Tk()
pane = Frame(master)
# Button 1
# Button 2
b2 = Button(pane, text = "Click me too")
# Execute Tkinter
master.mainloop()
Output:
Code #2: Placing widgets on top of each other and side by side. We can do
this by side option.
Python3
# creating Tk window
master = Tk()
pane = Frame(master)
# Button 1
# Button 2
# Button 3
# Execute Tkinter
master.mainloop()
Output:
Code #3:
Python3
# creating Tk window
master = Tk()
pane = Frame(master)
# Button 1
# Button 2
# Button 3
# Execute Tkinter
master.mainloop()
Output:
CHAPTER 4: forget_pack() and
forget_grid() method in Tkinter
Syntax: widget.forget_pack()
Code #1:
# toplevel window
root = Tk()
def forget(widget):
# This will remove the widget from toplevel
widget.forget()
def retrieve(widget):
# Button widgets
mainloop()
Output:
After forget
After retrieval
Notice the difference in the position of Button 1 before and after forget as
well as after retrieval.
forget_grid() method –
Syntax: widget.forget_grid()
Note : This method can be used only with grid() geometry methods.
Code #2:
# toplevel window
root = Tk()
def forget(widget):
widget.grid_forget()
# Button widgets
mainloop()
Output:
After Forget
After Retrieval
Notice that the position of Button 1 remains same after forget and retrieval.
With grid_forget() method, you can place it at any grid after retrieval but
generally, the original grid is chosen.
root = Tk()
# panedwindow object
pw = PanedWindow(orient ='vertical')
# Button widget
top.pack(side = TOP)
pw.add(top)
# Checkbutton Widget
bot.pack(side = TOP)
pw.configure(sashrelief = RAISED)
mainloop()
Output:
root = Tk()
# panedwindow object
pw = PanedWindow(orient ='vertical')
# Button widget
top.pack(side = TOP)
pw.add(top)
# Checkbutton Widget
bot.pack(side = TOP)
pw.add(bot)
label.pack(side = TOP)
pw.add(label)
# Tkinter string variable
string = StringVar()
entry.pack()
entry.focus_force()
pw.add(entry)
pw.configure(sashrelief = RAISED)
mainloop()
Output:
Python3
root = Tk()
# Execute Tkinter
root.mainloop()
Output:
As soon as you run the application, you’ll see the position of the Tkinter
window is at the northwest position of the screen and the size of the window
is also small as shown in the output below.
Tkinter window without geometry method
Python3
# are needed
root.geometry('200x150')
# Execute Tkinter
root.mainloop()
Output:
After running the application, you’ll see that the size of the Tkinter window
has changed, but the position on the screen is the same.
geometry method to set window dimensions
Python3
# are needed
root = Tk()
# creating fixed geometry of the
root.geometry('200x150+400+300')
# Execute Tkinter
root.mainloop()
Output:
When you run the application, you’ll observe that the position and size both
are changed. Now the Tkinter window is appearing at a different position
(400 shifted on X-axis and 300 shifted on Y-axis).
geometry method to set the dimensions and position of the Tkinter window
Note: We can also pass a variable argument in the geometry method, but it
should be in the form (variable1) x (variable2); otherwise, it will raise an
error.
Label:
Tkinter Label is a widget that is used to implement display boxes where you
can place text or images. The text displayed by this widget can be changed
by the developer at any time you want. It is also used to perform tasks such
as to underline the part of the text and span the text across multiple lines.
Example:
import tkinter as tk
root = tk.Tk()
Label_middle = tk.Label(root,
text ='Middle')
# root window
Label_middle.place(relx = 0.5,
rely = 0.5,
anchor = 'center')
# Execute Tkinter
root.mainloop()
Output:
Python3
# Import Module
import tkinter as tk
# Create Object
root = tk.Tk()
Lower_left.place(relx = 0.0,
rely = 1.0,
anchor ='sw')
# Execute Tkinter
root.mainloop()
Output
Example 3: Placing label at the upper right side of window
Python3
# Import Module
import tkinter as tk
# Create Object
root = tk.Tk()
# Create Label and add some text
Upper_right.place(relx = 1.0,
rely = 0.0,
anchor ='ne')
# Execute Tkinter
root.mainloop()
Output
PART 5: Binding Functions
Python3
# by tkinter.ttk
from tkinter import *
root = Tk()
root.geometry('200x100')
def enter(event):
def exit_(event):
frame1.bind('<Enter>', enter)
frame1.bind('<Leave>', exit_)
frame1.pack()
mainloop()
Python3
# Import all files from
# by tkinter.ttk
root = Tk()
root.geometry('200x100')
def pressed2(event):
def pressed3(event):
print('Button-3 pressed at x = % d, y = % d'%(event.x, event.y))
def double_click(event):
frame1.bind('<Button-2>', pressed2)
frame1.bind('<Button-3>', pressed3)
frame1.pack()
mainloop()
Code #3: Binding keyboard buttons with the root window (tkinter main
window).
Python3
# Import all files from
# by tkinter.ttk
def key_press(event):
key = event.char
root = Tk()
root.geometry('200x100')
root.bind('<Key>', key_press)
mainloop()
Note: When we bind keyboard buttons with the tkinter window, whenever
we press special characters we will only get space while in the case of
alphabets and numerical we will get actual values (in the string).
CHAPTER 2: Binding Function with
double click with Tkinter ListBox
def go(event):
cs = Lb.curselection()
w.config(text=Lb.get(cs))
if list == 0:
top.configure(background='red')
elif list == 1:
top.configure(background='green')
elif list == 2:
top.configure(background='yellow')
elif list == 3:
top.configure(background='white')
top = Tk()
top.geometry('250x275')
top.title('Double Click')
# Creating Listbox
Lb = Listbox(top, height=6)
Lb.insert(0, 'Red')
Lb.insert(1, 'Green')
Lb.insert(2, 'Yellow')
Lb.insert(3, 'White')
Lb.bind('<Double-1>', go)
Lb.pack()
w = Label(top, text='Default')
w.pack()
top.mainloop()
Output:
import tkinter
root = Tk()
Explanation:
The Label widget is used to display text or images corresponding to a
widget.The text displayed on the screen can further be formatted using the
other options available under Label widget.
L.pack()
Syntax: pack(options)
Parameter:
Explanation:
The pack() method is used to position the child widget in the parent
widget.
m = Menu(root, tearoff=0)
Explanation:
The tearoff is used to detach menus from the main window creating
floating menus. If tearoff=1, it creates a menu with dotted lines at the top
which when clicked the menu tears off the parent window and becomes
floating. To restrict the menu in the main window tearoff=0 here.
m.add_command(label="Rename")
Syntax: add_command(options)
Parameter:
Explanation:
The add_command() method adds menu items to the menu. The
add_separator() creates a thin line between the menu items.
13.
def do_popup(event):
14.
try:
15.
m.tk_popup(event.x_root, event.y_root)
16.
finally:
17.
m.grab_release()
18.
Syntax: tk_popup(x_root, y_root)
Parameter: This procedure posts a menu at a given position on the
screen, x_root and y_root is the current mouse position relative to the
upper left corner of the screen.
Explanation:
This method is the event handler. When the event(right click)
happens the method is called and the menu appears on the parent
widget at the position where the event occurs. The finally block
ensures that the grab_release() method releases the event grab.
19.
L.bind("<Button-3>", do_popup)
Syntax: bind(event, handler)
Parameter:
Explanation:
The right mouse button is pressed with the mouse pointer over the widget
and this triggers an event which is handled by the event handler(
do_popup() function ). The do_popup() function displays the menu.
20.
Run the application
mainloop()
Syntax: mainloop()
Parameter: Takes no arguments.
Explanation:
It acts like an infinite loop which keeps the application running until the
main window is closed manually.
import tkinter
root = Tk()
L.pack()
m = Menu(root, tearoff = 0)
m.add_command(label ="Cut")
m.add_command(label ="Copy")
m.add_command(label ="Paste")
m.add_command(label ="Reload")
m.add_separator()
m.add_command(label ="Rename")
def do_popup(event):
try:
m.tk_popup(event.x_root, event.y_root)
finally:
m.grab_release()
L.bind("<Button-3>", do_popup)
mainloop()
Output
There are numerous tools for designing GUI (Graphical User Interface) in
Python such as tkinter, wxPython, JPython, etc where Tkinter is the standard
Python GUI library, it provides a simple and efficient way to create GUI
applications in Python.
In Anaconda prompt:
import tkinter
import os
root = tkinter.Tk()
img = ImageTk.PhotoImage(Image.open("gfg.jpeg"))
expand = "yes")
root.mainloop()
Output:
In the above program, an image is loaded using the PhotoImage() method and
then it is read by using the Label() method.The pack() method arranges the main
window and the mainloop() function is used to run the application in an infinite
loop.
Example 2: Let us look at another example where we arrange the image
parameters along with application parameters.
# importing required packages
import tkinter
root = tkinter.Tk()
height = 250)
canvas.pack()
img = ImageTk.PhotoImage(Image.open("gfg.ppm"))
# in the application
image = img)
Output:
master = Tk()
master.iconphoto(False, photo)
Set the titlebar icon for this window based on the named photo images
passed through args. If default is True, this is applied to all future created
toplevels as well. The data in the images is taken as a snapshot at the time of
invocation. If the images are later changed, this is not reflected in
the titlebar icons. The function also scales provided icons to an appropriate
size.
Code #1: When PhotoImage is provided.
Python3
master = Tk()
# Creating object of photoimage class
p1 = PhotoImage(file = 'info.png')
master.iconphoto(False, p1)
# Creating button
b.pack(side = TOP)
mainloop()
Output:
Python3
master = Tk()
master.iconphoto(False, 'info.png')
# Creating button
b.pack(side = TOP)
mainloop()
Output:
Traceback (most recent call last):
File "C:\Users\Admin\Documents\GUI_python\geeks.py", line 14, in
master.iconphoto(False, 'info.png')
File "C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line
1910, in wm_iconphoto
Importing modules –
Python3
Note: The ImageTk module contains support to create and modify Tkinter
BitmapImage and PhotoImage objects from PIL images and filedialog is
used for the dialog box to appear when you are opening file from anywhere
in your system or saving your file in a particular position or place.
Python3
# Create a window
root = Tk()
root.title("Image Loader")
row = 1, columnspan = 4)
root.mainloop()
The Button object is created with text ‘open image’. On clicking it the
open_image function will be invoked.
Function to place the image onto the window –
Python3
def open_img():
x = openfilename()
img = Image.open(x)
img = ImageTk.PhotoImage(img)
# create a label
panel.image = img
panel.grid(row = 2)
Python3
def openfilename():
return filename
To run this code, save it by the extension .py and then open cmd (command
prompt) and move to the location of the file saved and then write the
following –
python "filename".py
and press enter and it will run. Or can be run directly by simply double-
clicking your .py extension file.
Output:
https://media.geeksforgeeks.org/wp-
content/uploads/20191121233525/Screencast-from-Thursday-21-November-
2019-111137-IST2.webm
PART 6: Applications and Projects
Python3
expression = ""
def press(num):
# point out the global expression variable
global expression
# concatenation of string
equation.set(expression)
def equalpress():
try:
global expression
# into string
total = str(eval(expression))
equation.set(total)
# by empty string
expression = ""
except:
expression = ""
def clear():
global expression
expression = ""
equation.set("")
# Driver code
if __name__ == "__main__":
gui = Tk()
gui.configure(background="light green")
gui.title("Simple Calculator")
gui.geometry("270x150")
equation = StringVar()
expression_field.grid(columnspan=4, ipadx=70)
# create a Buttons and place at a particular
button1.grid(row=2, column=0)
button2.grid(row=2, column=1)
button3.grid(row=2, column=2)
button4.grid(row=3, column=0)
button5.grid(row=3, column=1)
button6.grid(row=3, column=2)
button7.grid(row=4, column=0)
button8.grid(row=4, column=1)
button9.grid(row=4, column=2)
button0.grid(row=5, column=0)
plus.grid(row=2, column=3)
multiply.grid(row=4, column=3)
divide.grid(row=5, column=3)
equal.grid(row=5, column=2)
clear.grid(row=5, column='1')
Decimal.grid(row=6, column=0)
gui.mainloop()
Code Explanation:
1. The code starts by importing the necessary modules.
2. The tkinter module provides all the basic functionality for creating
graphical user interfaces.
3. Next, we create a global variable called expression which will store
the result of the calculation.
4. We also create two functions to update and evaluate the expression.
5. Finally, we write driver code to initialize and manage our GUI
window.
6. In order to create a simple calculator, we first need to define an
expression variable.
7. This is done by using the global keyword and assigning it an empty
string value ( “” ).
8. Next, we create two functions to update and evaluate the expression.
9. The press function updates the contents of the text entry box while
equalpress evaluates the final result of the calculation.
10.
We next need to create a table-like structure in which our widgets
will be placed.
11.
We do this by using grid method which takes three arguments:
columnspan , ipadx , and rowspan .
12.
These parameters specify how many columns wide, how many
rows high, and how many columns per row respectively should be
used in our table layout.
13.
We set columnspan to 4 , meaning that there will be four columns
in our table, iPad width divided by 2 (70), multiplied by 1 for each
row in our table (iPad height divided
14.
The code creates a simple calculator using the Tkinter module.
15.
First, the code imports everything from the Tkinter module.
16.
Next, the code creates two global variables: expression and total.
17.
The press() function is used to update the expression variable in
the text entry box.
18.
The equalpress() function is used to evaluate the final expression.
19.
Finally, the clear() function is used to clear the contents of the text
entry box.
20.
Next, the driver code is created.
21.
In this code, if __name__ == “__main__”: is executed which will
create a GUI window and set its background color to light green and
its title to Simple Calculator.
22.
Next, the geometry() method is used to set the size of the GUI
window (270
23.
The code starts with a few basic objects: a Button object, which
has properties for text, font, background color, and command; and a
grid object.
24.
The first three buttons (button1 through button3) each have their
own individual commands associated with them.
25.
When the user clicks on one of these buttons, the corresponding
command is executed.
26.
For example, when the user clicks on button1, its command is to
press the number 1 key.
27.
Similarly, when the user clicks on button2’s command, it will be to
press the number 2 key; and so on.
28.
Similarly, when the user clicks on button4’s command (to increase
the value by 1), its grid row and column values will be set to 3 and 0
respectively.
29.
And finally when clicking on button5’s command (to decrease the
value by 1), its grid row and column values will be set to 2 and 1
respectively.
30.
The code creates seven buttons, each with its own function.
31.
When the user presses one of the buttons, the corresponding
command is executed.
32.
The first button, button1, has the function press(1).
33.
When clicked, this button will execute the code lambda: press(1).
34.
The second button, button2, has the function press(2), and so on.
35.
When all seven buttons have been clicked, their functions will be
executed in order.
import tkinter
top = tkinter.Tk()
top.mainloop()
Output:
Creating Stopwatch using Tkinter
Now lets try to create a program using Tkinter module to create a stopwatch.
A stopwatch is a handheld timepiece designed to measure the amount of time
elapsed from a particular time when it is activated to the time when the piece
is deactivated. A large digital version of a stopwatch designed for viewing at
a distance, as in a sports stadium, is called a stop clock. In manual timing, the
clock is started and stopped by a person pressing a button. In fully automatic
time, both starting and stopping are triggered automatically, by sensors.
Required Modules: We are only going to use Tkinter for creating GUI and
no other libraries will be used in this program.
Source Code:
Python3
# using Tkinter
counter = 66600
running = False
def counter_label(label):
def count():
if running:
global counter
# To manage the initial delay.
if counter==66600:
display="Starting..."
else:
tt = datetime.fromtimestamp(counter)
string = tt.strftime("%H:%M:%S")
display=string
label['text']=display # Or label.config(text=display)
label.after(1000, count)
counter += 1
count()
global running
running=True
counter_label(label)
start['state']='disabled'
stop['state']='normal'
reset['state']='normal'
def Stop():
global running
start['state']='normal'
stop['state']='disabled'
reset['state']='normal'
running = False
def Reset(label):
global counter
counter=66600
reset['state']='disabled'
label['text']='Welcome!'
else:
label['text']='Starting...'
root = Tkinter.Tk()
root.title("Stopwatch")
root.minsize(width=250, height=70)
label.pack()
f = Tkinter.Frame(root)
f.pack(anchor = 'center',pady=5)
start.pack(side="left")
stop.pack(side ="left")
reset.pack(side="left")
root.mainloop()
Output:
Let’s create a GUI based simple real-time currency converter (Using Alpha
Vantage API) which can convert amounts from one currency to another
currency.
Requirements:
tkinter
requests
json
Note: You need an API key to use the Alpha Vantage API.
Complete code:
Python3
root = Tk()
# create a global variables
variable1 = StringVar(root)
variable2 = StringVar(root)
variable1.set("currency")
variable2.set("currency")
def RealTimeCurrencyConversion():
# currency code
from_currency = variable1.get()
to_currency = variable2.get()
api_key = "Your_Api_Key"
# base_url variable store base url
base_url = r"https://www.alphavantage.co/query?function =
CURRENCY_EXCHANGE_RATE"
req_ob = requests.get(main_url)
result = req_ob.json()
amount = float(Amount1_field.get())
Amount2_field.insert(0, str(new_amount))
def clear_all():
Amount1_field.delete(0, END)
Amount2_field.delete(0, END)
# Driver code
if __name__ == "__main__" :
root.geometry("400x175")
fg = 'black', bg = "red")
headlabel.grid(row = 0, column = 1)
label1.grid(row = 1, column = 0)
label2.grid(row = 2, column = 0)
label3.grid(row = 3, column = 0)
label4.grid(row = 5, column = 0)
Amount1_field = Entry(root)
Amount2_field = Entry(root)
command = RealTimeCurrencyConversion)
button1.grid(row = 4, column = 1)
button2.grid(row = 6, column = 1)
# Start the GUI
root.mainloop()
Output :
CHAPTER 4: Create Table Using Tkinter
for i in range(5):
for j in range(4):
Now, we need logic to place this Entry widget in rows and columns. This can
be done by using grid() method to which we can pass row and column
positions, as:
We can insert data into the Entry widget using insert() method, as:
e.insert(END, data)
Here, ‘END’ indicates that the data continuous to append at the end of
previous data in the Entry widget.
This is the logic that is used in the program given below using the data that is
coming from a list. We have taken a list containing 5 tuples and each tuple
contains four values which indicate student id, name, city and age.
Hence, we will have a table with 5 rows and 4 columns in each row. This
program can also be applied on data coming from a database to display the
entire data in the form of a table.
Source Code:
Python3
class Table:
def __init__(self,root):
for i in range(total_rows):
for j in range(total_columns):
font=('Arial',16,'bold'))
self.e.grid(row=i, column=j)
self.e.insert(END, lst[i][j])
lst = [(1,'Raj','Mumbai',19),
(2,'Aaryan','Pune',18),
(3,'Vaishnavi','Mumbai',20),
(4,'Rachna','Mumbai',21),
(5,'Shubham','Delhi',21)]
# columns in list
total_rows = len(lst)
total_columns = len(lst[0])
root = Tk()
t = Table(root)
root.mainloop()
Output:
To create a Tkinter:
import calendar
def showCal() :
# Create a GUI window
new_gui = Tk()
new_gui.config(background = "white")
new_gui.title("CALENDAR")
new_gui.geometry("550x600")
fetch_year = int(year_field.get())
cal_content = calendar.calendar(fetch_year)
new_gui.mainloop()
# Driver Code
if __name__ == "__main__" :
gui = Tk()
gui.config(background = "white")
gui.title("CALENDAR")
gui.geometry("250x140")
year_field = Entry(gui)
cal.grid(row = 1, column = 1)
year.grid(row = 2, column = 1)
year_field.grid(row = 3, column = 1)
Show.grid(row = 4, column = 1)
Exit.grid(row = 6, column = 1)
gui.mainloop()
Code Explanation:
1. The code starts by creating a new Tkinter window.
2. The window has a white background and the title “CALENDAR”.
3. Next, the window’s geometry is set to be 550×600 pixels.
4. The calendar module is imported and the showCal() function is
defined.
5. This function will be used to display the calendar for the given year.
6. The showCal() function first creates a GUI window and sets its
background color to white.
7. It also sets the title of the GUI window to “CALENDAR”.
8. Finally, it sets the configuration of the GUI window.
9. Next, two labels are created: CALENDAR and ENTER YEAR.
10.
CALENDAR’s text is set to be “CALENDAR”, its background
color is changed from white to dark gray, and its font size is set to 28
points bold.
11.
ENTER YEAR’s text is set to be “Enter Year”, its background
color is changed from light green to red, and its font size is set to 10
points bold.
12.
A text entry box named year_field is created next and assigned as
an attribute of year_field object instance .
13.
Finally, a Show Calendar button (with appropriate attributes) and
an Exit button (with appropriate attributes) are created and
14.
The code creates a window and sets its background color to white.
15.
The window’s title is set to “CALENDAR” and its geometry is set
to 550×600.
16.
The calendar module is imported and the method
calendar.calendar() is called with the given year as an argument.
17.
This returns the calendar for the given year.
18.
A label named cal_year is created and it has a grid with five rows
and one column.
19.
The first row of the grid will be at position (5, 1), the second row
at (4, 1), etc., until row 5 which will be at position (0, 0).
20.
Similarly, column 1 will be at position (0, 0), column 2 at (1, 0).
Prerequisites:
In order to do so, we have to import the filedialog module from Tkinter. The
File dialog module will help you open, save files or directories.
In order to open a file explorer, we have to use the method,
askopenfilename(). This function creates a file dialog object.
Python3
def browseFiles():
filename = filedialog.askopenfilename(initialdir = "/",
"*.txt*"),
("all files",
"*.*")))
window = Tk()
window.title('File Explorer')
window.geometry("500x500")
window.config(background = "white")
# Create a File Explorer label
label_file_explorer = Label(window,
fg = "blue")
button_explore = Button(window,
command = browseFiles)
button_exit = Button(window,
text = "Exit",
command = exit)
label_file_explorer.grid(column = 1, row = 1)
button_explore.grid(column = 1, row = 2)
button_exit.grid(column = 1,row = 3)
window.mainloop()
Output:
Conclusion
This book is dedicated to the readers who take time to write me each day. Every morning I’m greeted
by various emails — some with requests, a few with complaints, and then there are the very few that
just say thank you. All these emails encourage and challenge me as an author — to better both my
Thank you!
OceanofPDF.com