Python Tkinter
Thank you Dr Ajay Kumar for sharing PPT
A graphical user interface (GUI) is an interface
through which a user interacts with electronic
devices such as computers and smartphones
through the use of icons, menus and other visual
INTRODUCTION
indicators or representations (graphics).
GUI representations are manipulated by a pointing
device such as a mouse, trackball, stylus, or by a
finger on a touch screen.
• Python provides the standard library Tkinter for creating
the graphical user interface for desktop based applications.
• Developing desktop based applications with python
Tkinter is not a complex task.
• An empty Tkinter top-level window can be created by
using the following steps.
INTRODUCTION 1. import the Tkinter module.
2. Create the main application window.
3. Add the widgets like labels, buttons, frames, etc. to the
window.
4. Call the main event loop so that the actions can take
place on the user's computer screen.
EXAMPLE Output:
from tkinter import *
#creating the application main window.
top = Tk()
#Entering the event main loop
top.mainloop()
import tkinter as tk
top = tk.Tk()
label = tk.Label(text="Hello, Tkinter")
label.pack()
top.mainloop()
Tkinter Widgets
There are various widgets like button, canvas, checkbutton, entry, etc. that are used to build the
python GUI applications.
SNo Widget Description
1 Button The Button is used to add various kinds of buttons to the python
application.
2 Canvas The canvas widget is used to draw the canvas on the window.
3 Checkbutton The Checkbutton is used to display the CheckButton on the window.
4 Entry The entry widget is used to display the single-line text field to the
user. It is commonly used to accept user values.
5 Frame It can be defined as a container to which, another widget can be
added and organized.
Tkinter Widgets
SNo Widget Description
6 Label A label is a text used to display some message or information about the other
widgets.
7 ListBox The ListBox widget is used to display a list of options to the user.
8 Menubutton The Menubutton is used to display the menu items to the user.
9 Menu It is used to add menu items to the user.
10 Message The Message widget is used to display the message-box to the user.
11 Radiobutton The Radiobutton is different from a checkbutton. Here, the user is provided with
various options and the user can select only one option among them.
12 Scale It is used to provide the slider to the user.
13 Scrollbar It provides the scrollbar to the user so that the user can scroll the window up and
down.
14 Text It is different from Entry because it provides a multi-line text field to the user so
that the user can write the text and edit the text inside it.
14 Toplevel It is used to create a separate window container.
15 Spinbox It is an entry widget used to select from options of values.
16 PanedWindow It is like a container widget that contains horizontal or vertical panes.
17 LabelFrame A LabelFrame is a container widget that acts as the container
18 MessageBox This module is used to display the message-box in the desktop based applications.
Adding a Widget
Use the tk.Label class to add some text to a window. Create a Label widget with the text "Hello, Tkinter" and
assign it to a variable called greeting:
label = tk.Label(text="Hello, Tkinter")
You just created a Label widget, but you haven’t added it to the window yet. There are several ways to add
widgets to a window. Right now, you can use the Label widget’s .pack() method:
label.pack()
Adding a Widget
import tkinter as tk
window = tk.Tk()
label = tk.Label(text="Python rocks!")
label.pack()
window.mainloop()
Displaying Text and Images with Label widget
Text:
label = tk.Label( text="Hello, Tkinter", fg="white",
bg="black", width=10, height=10 )
Image:
photo = PhotoImage(file="1.png")
label = tk.Label( image=photo, width=10, height=10 )
Displaying Clickable Buttons With Button Widgets
button = tk.Button( text="Click me!", width=25, height=5, bg="blue", fg="yellow", )
Getting User Input with Entry Widgets
When you need to get a little bit of text from a user, like a name or an email address, use an Entry widget.
It’ll display a small text box that the user can type some text into.
entry = tk.Entry(fg="yellow", bg="blue", width=50)
There are three main operations that you can perform with Entry widgets:
1. Retrieving text with .get()
2. Deleting text with .delete()
3. Inserting text with .insert()
Getting User Input with Entry Widgets
import tkinter as tk
window = tk.Tk()
label = tk.Label(text="Name")
entry = tk.Entry()
label.pack()
entry.pack()
>>> name = entry.get()
>>> name
'Real Python'
Getting User Input with Entry Widgets
entry.delete(0)
entry.delete(0, 4)
entry.delete(0, tk.END)
Getting User Input with Entry Widgets
entry.insert(0, "Python")
entry.insert(0, "Real ")
Getting Multiline User Input With Text Widgets
Text widgets are used for entering text, just like Entry widgets. The difference is that Text widgets may
contain multiple lines of text. With a Text widget, a user can input a whole paragraph or even several
pages of text! Just like with Entry widgets, you can perform three main operations with Text widgets:
1. Retrieve text with .get()
2. Delete text with .delete()
3. Insert text with .insert()
Getting Multiline User Input With Text Widgets
window = tk.Tk()
text_box = tk.Text()
text_box.pack()
Retrieve text with .get()
Text.get() requires at least one argument. Calling .get() with a single index returns a single character. To
retrieve several characters, you need to pass a start index and an end index. Indices in Text widgets work
differently than in Entry widgets. Since Text widgets can have several lines of text, an index must contain
two pieces of information:
1.The line number of a character text_box.get("1.0")
'H'
2.The position of a character on that line
text_box.get("1.0", "1.5")
'Hello'
text_box.get("2.0", "2.5")
'World'
text_box.get("1.0", tk.END)
'Hello\nWorld\n'
Delete text with .delete()
.delete() is used to delete characters from a text box. It works just like .delete() for Entry widgets. There
are two ways to use .delete():
1.With a single argument
2.With two arguments
text_box.delete("1.0")
text_box.delete("1.0", "1.4")
text_box.get("1.0")
'\n'
text_box.delete("1.0")
text_box.delete("1.0", tk.END)
Insert text with .insert()
text_box.insert("1.0", "Hello")
text_box.insert("2.0", "World")
text_box.insert("2.0", "\nWorld")
.insert() will do one of two things:
1.Insert text at the specified position if there’s already text at or after that position.
2.Append text to the specified line if the character number is greater than the index of the last character in the
text box.
text_box.insert(tk.END, "Put me at the end!")
text_box.insert(tk.END, "\nPut me on a new line!")
Python Tkinter Geometry
The Tkinter geometry specifies the method by using which, the widgets are
represented on display. The python Tkinter provides the following geometry
methods.
The pack() method
The grid() method
The place() method
Python Tkinter pack() method
The pack() widget is used to organize widget in the block. The positions widgets added to the python
application using the pack() method can be controlled by using the various options specified in the
method call.
Syntax: widget.pack(options)
A list of possible options that can be passed in pack() is given below.
• expand: If the expand is set to true, the widget expands to fill any space.
• Fill: By default, the fill is set to NONE. However, we can set it to X or Y to determine whether the
widget contains any extra space.
• size: it represents the side of the parent to which the widget is to be placed on the window.
EXAMPLE
from tkinter import *
parent = Tk()
redbutton = Button(parent, text = "Red", fg = "red")
redbutton.pack( side = LEFT)
greenbutton = Button(parent, text = "Black", fg = "black")
greenbutton.pack( side = RIGHT )
Output:
bluebutton = Button(parent, text = "Blue", fg = "blue")
bluebutton.pack( side = TOP )
blackbutton = Button(parent, text = "Green", fg = "red")
blackbutton.pack( side = BOTTOM)
parent.mainloop()
EXAMPLE
import tkinter as tk
window = tk.Tk()
frame1 = tk.Frame(master=window, width=100, height=100, bg="red")
frame1.pack() frame2 = tk.Frame(master=window, width=50, height=50, bg="yellow")
frame2.pack()
frame3 = tk.Frame(master=window, width=25, height=25, bg="blue")
frame3.pack()
Output:
window.mainloop()
EXAMPLE
import tkinter as tk
window = tk.Tk()
frame1 = tk.Frame(master=window, width=200, height=100, bg="red")
frame1.pack(fill=tk.Y, side=tk.LEFT)
frame2 = tk.Frame(master=window, width=100, bg="yellow")
frame2.pack(fill=tk.Y, side=tk.LEFT) Output:
frame3 = tk.Frame(master=window, width=50, bg="blue")
frame3.pack(fill=tk.Y, side=tk.LEFT)
window.mainloop()
EXAMPLE
import tkinter as tk
window = tk.Tk()
frame1 = tk.Frame(master=window, width=200, height=100, bg="red")
frame1.pack(fill=tk.BOTH, side=tk.LEFT, expand=True)
frame2 = tk.Frame(master=window, width=100, bg="yellow")
frame2.pack(fill=tk.BOTH, side=tk.LEFT, expand=True) Output:
frame3 = tk.Frame(master=window, width=50, bg="blue")
frame3.pack(fill=tk.BOTH, side=tk.LEFT, expand=True)
window.mainloop()
Python Tkinter grid() method
The grid() geometry manager organizes the widgets in the tabular form. We can specify the rows and columns as
the options in the method call. We can also specify the column span (width) or rowspan(height) of a widget.
Syntax : widget.grid(options)
A list of possible options that can be passed inside the grid() method is given below.
• Column : The column number in which the widget is to be placed. The leftmost column is represented by 0.
• Columnspan : The width of the widget. It represents the number of columns up to which, the column is expanded.
• ipadx, ipady : It represents the number of pixels to pad the widget inside the widget's border.
• padx, pady : It represents the number of pixels to pad the widget outside the widget's border.
• row : The row number in which the widget is to be placed. The topmost row is represented by 0.
• rowspan : The height of the widget, i.e. the number of the row up to which the widget is expanded.
• sticky : If the cell is larger than a widget, then sticky is used to specify the position of the widget inside the cell. It may be
the concatenation of the sticky letters representing the position of the widget. It may be N, E, W, S, NE, NW, NS, EW, ES.
EXAMPLE
from tkinter import *
parent = Tk()
name = Label(parent,text = "Name").grid(row = 0, column = 0)
e1 = Entry(parent).grid(row = 0, column = 1)
password = Label(parent,text = "Password").grid(row = 1, column = 0)
e2 = Entry(parent).grid(row = 1, column = 1)
submit = Button(parent, text = "Submit").grid(row = 4, column = 0)
parent.mainloop() Output:
EXAMPLE
import tkinter as tk window = tk.Tk()
for i in (3):
for j in (3):
frame = tk.Frame( master=window, relief=tk.RAISED, borderwidth=1 )
frame.grid(row=i, column=j)
label = tk.Label(master=frame, text=f"Row {i}\nColumn {j}")
label.pack()
window.mainloop()
EXAMPLE
import tkinter as tk
window = tk.Tk()
for i in (3):
for j in (3):
frame = tk.Frame( master=window, relief=tk.RAISED, borderwidth=1 )
frame.grid(row=i, column=j, padx=5, pady=5)
label = tk.Label(master=frame, text=f"Row {i}\nColumn {j}")
label.pack(padx=5, pady=5)
window.mainloop()
EXAMPLE
import tkinter as tk
window = tk.Tk()
for i in (3):
window.columnconfigure(i, weight=1, minsize=75)
window.rowconfigure(i, weight=1, minsize=50)
for j in (0, 3):
frame = tk.Frame( master=window, relief=tk.RAISED, borderwidth=1 )
frame.grid(row=i, column=j, padx=5, pady=5)
label = tk.Label(master=frame, text=f"Row {i}\nColumn {j}")
label.pack(padx=5, pady=5)
window.mainloop()
EXAMPLE
Python Tkinter place() method
The place() geometry manager organizes the widgets to the specific x and y coordinates.
Syntax :
widget.place(options) , A list of possible options is given below
Anchor: It represents the exact position of the widget within the container. The default value (direction) is NW
(the upper left corner)
bordermode: The default value of the border type is INSIDE that refers to ignore the parent's inside the border.
The other option is OUTSIDE.
height, width: It refers to the height and width in pixels.
relheight, relwidth: It is represented as the float between 0.0 and 1.0 indicating the fraction of the parent's
height and width.
relx, rely: It is represented as the float between 0.0 and 1.0 that is the offset in the horizontal and vertical
direction.
x, y: It refers to the horizontal and vertical offset in the pixels.
EXAMPLE
from tkinter import *
top = Tk()
top.geometry("400x250")
name = Label(top, text = "Name").place(x = 30,y = 50)
email = Label(top, text = "Email").place(x = 30, y = 90)
Output:
password = Label(top, text = "Password").place(x = 30, y = 130)
e1 = Entry(top).place(x = 80, y = 50)
e2 = Entry(top).place(x = 80, y = 90)
e3 = Entry(top).place(x = 95, y = 130)
top.mainloop()
Assigning Widgets to Frames With Frame Widget
import tkinter as tk
window = tk.Tk()
frame = tk.Frame()
frame.pack()
window.mainloop()
frame = tk.Frame()
label = tk.Label(master=frame)
Assigning Widgets to Frames With Frame Widget
import tkinter as tk
window = tk.Tk()
frame_a = tk.Frame()
frame_b = tk.Frame()
label_a = tk.Label(master=frame_a, text="I'm in Frame A")
label_a.pack()
label_b = tk.Label(master=frame_b, text="I'm in Frame B")
label_b.pack()
frame_a.pack()
frame_b.pack()
window.mainloop()
Adjusting Frame Appearance With Reliefs
Frame widgets can be configured with a relief attribute that creates a border around
the frame. You can set relief to be any of the following values:
•tk.FLAT: Has no border effect (the default value)
•tk.SUNKEN: Creates a sunken effect
•tk.RAISED: Creates a raised effect
•tk.GROOVE: Creates a grooved border effect
•tk.RIDGE: Creates a ridged effect
Example
import tkinter as tk
border_effects = { "flat": tk.FLAT,
"sunken": tk.SUNKEN,
"raised": tk.RAISED,
"groove": tk.GROOVE,
"ridge": tk.RIDGE, }
window = tk.Tk()
for relief_name, relief in border_effects.items():
frame = tk.Frame(master=window, relief=relief, borderwidth=5)
frame.pack(side=tk.LEFT)
label = tk.Label(master=frame, text=relief_name)
label.pack()
window.mainloop()
Exercise
Write a full Python script that creates a Tkinter window with the text "Python rocks!".
Write a complete script that displays an Entry widget that’s 40 text units wide and has
a white background and black text. Use .insert() to display text in the widget that reads
What is your name?.
Exercise
Create an address entry form.
import tkinter as tk
def increase():
value = int(lbl_value["text"])
lbl_value["text"] = f"{value + 1}“
def decrease():
value = int(lbl_value["text"])
lbl_value["text"] = f"{value - 1}“
window = tk.Tk()
window.rowconfigure(0, minsize=50, weight=1)
window.columnconfigure([0, 1, 2], minsize=50, weight=1)
btn_decrease = tk.Button(master=window, text="-", command=decrease)
btn_decrease.grid(row=0, column=0, sticky="nsew")
lbl_value = tk.Label(master=window, text="0")
lbl_value.grid(row=0, column=1)
btn_increase = tk.Button(master=window, text="+", command=increase)
btn_increase.grid(row=0, column=2, sticky="nsew")
window.mainloop()
Exercise
Write a program that simulates rolling a six-sided die. There should be one button with the text Roll.
When the user clicks the button, a random integer from 1 to 6 should be displayed.
Exercise
Write a program for temperature converter.