0% found this document useful (0 votes)
185 views26 pages

Python Tkinter Tutorial

Uploaded by

pratheepgtec
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
185 views26 pages

Python Tkinter Tutorial

Uploaded by

pratheepgtec
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 26

Python Tkinter

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.
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
# !/usr/bin/python3 from tkinter
import *
#creating the application main window.
top = Tk()
#Entering the event main loop top.mainloop()

Tkinter widgets
There are various widgets like button, canvas, checkbutton, entry, etc. that are used to build
the python GUI applications.

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

1
5 Frame

It can be defined as a container to which, another widget can be


added and organized.

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.

2
15 Spinbox It is an entry widget used to select from options of values.

It is like a container widget that contains horizontal or vertical


16 PanedWindow 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.

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.
1. The pack() method
2. The grid() method
3. The place() method
Let's discuss each one of them in detail.
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.
However, the controls are less and widgets are generally added in the less organized manner.
The syntax to use the pack() is given below.
syntax
widget.pack(options)
A list of possible options that can be passed in pack() is given below.
o expand: If the expand is set to true, the widget expands to fill any space.
o 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.
o size: it represents the side of the parent to which the widget is to be placed on the
window.

Example
# !/usr/bin/python3
from tkinter import *
parent = Tk()
redbutton = Button(parent, text = "Red", fg = "red")

3
redbutton.pack( side = LEFT)
greenbutton = Button(parent, text = "Black", fg = "black")
greenbutton.pack( side = RIGHT )
bluebutton = Button(parent, text = "Blue", fg = "blue")
bluebutton.pack( side = TOP )
blackbutton = Button(parent, text = "Green", fg = "red")
blackbutton.pack( side = BOTTOM)
parent.mainloop()
Output:

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.
This is a more organized way to place the widgets to the python application. The syntax to use
the grid() is given below.
Syntax
widget.grid(options)
A list of possible options that can be passed inside the grid() method is given below.
o Column
The column number in which the widget is to be placed. The leftmost column is
represented by 0.
o Columnspan
The width of the widget. It represents the number of columns up to which, the
column is expanded.
o ipadx, ipady
It represents the number of pixels to pad the widget inside the widget's border.
o padx, pady
It represents the number of pixels to pad the widget outside the widget's border.
o row
The row number in which the widget is to be placed. The topmost row is represented
by 0.
o rowspan
The height of the widget, i.e. the number of the row up to which the widget is
expanded.
o 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.

4
AD

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:

Python Tkinter place() method


The place() geometry manager organizes the widgets to the specific x and y coordinates.
AD
Syntax
1. widget.place(options)
A list of possible options is given below.
o Anchor: It represents the exact position of the widget within the container. The
default value (direction) is NW (the upper left corner)
o 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.
o height, width: It refers to the height and width in pixels.
o relheight, relwidth: It is represented as the float between 0.0 and 1.0 indicating the
fraction of the parent's height and width.
o relx, rely: It is represented as the float between 0.0 and 1.0 that is the offset in the
horizontal and vertical direction.
o 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)
password = Label(top, text = "Password").place(x = 30, y= 130)

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

Output:

Python Tkinter Button


The button widget is used to add various types of buttons to the python application. Python
allows us to configure the look of the button according to our requirements. Various options
can be set or reset depending upon the requirements.
We can also associate a method or function with a button which is called when the button is
pressed.
The syntax to use the button widget is given below.
Syntax
W = Button(parent, options)
A list of possible options is given below.

SN Option Description

1 activebackground
It represents the background of the button when the mouse hover
the button.
2 activeforeground
It represents the font color of the button when the mouse hover
the button.

6
3 Bd It represents the border width in pixels.

4 Bg It represents the background color of the button.

5 Command

It is set to the function call which is scheduled when the function


is called.

6 Fg Foreground color of the button.

7 Font The font of the button text.


8 Height
The height of the button. The height is represented in the
number of text lines for the textual lines or the number of pixels
for the images.

Example

from tkinter import *


top = Tk()
top.geometry("200x100")
b = Button(top,text = "Simple")
b.pack()
top.mainaloop()

Output:

Example
from tkinter import *
top= Tk()
top.geometry("200x100")

7
def fun():
messagebox.showinfo("Hello", "Red Button clicked")
b1 = Button(top,text = "Red",command = fun,activeforeground = "red",active background =
"pink",pady=10)
b2 = Button(top, text = "Blue",activeforeground = "blue",activebackground = "pink",pady=10)
b3 = Button(top, text = "Green",activeforeground = "green",activebackground ="pink",
pady = 10)
b4 = Button(top, text = "Yellow",activeforeground = "yellow",activebackground = "pink",
pady = 10)
b1.pack(side = LEFT)
b2.pack(side = RIGHT)
b3.pack(side = TOP)
b4.pack(side = BOTTOM)
top.mainloop()

Output:

Python Tkinter Entry


The Entry widget is used to provde the single line text-box to the user to accept a value from
the user. We can use the Entry widget to accept the text strings from the user. It can only be
used for one line of text from the user. For multiple lines of text, we must use the text widget.
The syntax to use the Entry widget is given below.
Syntax
w = Entry (parent, options)

List of possible options is given below.

SN Option Description

1 bg The background color of the widget.

8
2 bd The border width of the widget in pixels.
3 fg It represents the color of the text.
4 font It represents the font type of the text.
5 justify It specifies how the text is organized if the text contains multiple
lines.
6 textvariable It is set to the instance of the StringVar to retrieve the text from
the entry.
7 width The width of the displayed text or image.

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)
password = Label(top, text = "Password").place(x = 30, y = 130)
submit= Button(top, text = "Submit",activebackground = "pink", activefore ground =
"blue").place(x = 30, y = 170)
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()

9
Output

Python Tkinter Label


The Label is used to specify the container box where we can place the text or images. This
widget is used to provide the message to the user about other widgets used in the python
application.
There are the various options which can be specified to configure the text or the part of the
text shown in the Label.
The syntax to use the Label is given below.
Syntax
w = Label (master, options)

List of possible options is given below.

SN Option Description

1 anchor
It specifies the exact position of the text within the size
provided to the widget. The default value is CENTER, which
is used to center the text within the specified space.

2 bg The background color displayed behind the widget.

3 bitmap
It is used to set the bitmap to the graphical object specified
so that, the label can represent the graphics instead of text.

4 bd It represents the width of the border. The default is 2 pixels.

10
5 cursor
The mouse pointer will be changed to the type of the cursor
specified, i.e., arrow, dot, etc.

6 font The font type of the text written inside the widget.

7 fg The foreground color of the text written inside the widget.

8 height The height of the widget.

9 image The image that is to be shown as the label.


10 justify It is used to represent the orientation of the text if the text
contains multiple lines. It can be set to LEFT for left
justification, RIGHT for right justification, and CENTER for
center justification.

Example 1

from tkinter import *


top = Tk()
top.geometry("400x250")
uname = Label(top, text = "Username").place(x = 30,y = 50)
password = Label(top, text = "Password").place(x = 30, y = 90)
submitbtn = Button(top, text = "Submit",activebackground = "pink", activeforeground
= "blue").place(x = 30, y = 120)
e1 = Entry(top,width = 20).place(x = 100, y = 50)
e2 = Entry(top, width = 20).place(x = 100, y = 90)
top.mainloop()

11
Output:

Python program that adds two numbers in Tkinter

import tkinter as tk
def add():
num1 = float(num1_entry.get())
num2 = float(num2_entry.get())
result = num1 + num2
result_label.config(text=("Sum:"+str(result)))

# create the main window

root=tk.Tk()
root.title("Add Two Numbers")

# create the widgets num1_


num1_label = tk.Label(root, text="Number 1:")
num1_entry = tk.Entry(root)
num2_label = tk.Label(root, text="Number 2:")
num2_entry = tk.Entry(root)
add_button = tk.Button(root, text="Add", command=add)
result_label = tk.Label(root, text="Result:")

12
# layout the widgets

num1_label.grid(row=0, column=0, sticky="e")


num1_entry.grid(row=0, column=1)
num2_label.grid(row=1, column=0, sticky="e")
num2_entry.grid(row=1, column=1)
add_button.grid(row=2, column=0, columnspan=2, pady=10)
result_label.grid(row=3, column=0, columnspan=2)

# run the main loop


root.mainloop()

Read 5 marks and find the Total & Average

from tkinter import*


def Ok ():
result = int(e1.get()) + int(e2.get()) + int(e3.get())+ int(e4.get())+ int(e5.get())
totText.set(result)
average = result/5
avgText.set(average)
if (average > 90):
grade = "A+"
elif(average>80):
grade="A"
elif(average>70):
grade="B"
elif(average>60):
grade="C"
elif(average>50):
grade="D"
elif(average>=40):
grade="E"
else:
grade = "fail"

gradeText.set(grade)

root = Tk()
root.title("Student Marks Calculation System") ‘
root.geometry("300x400")

13
global e1
global e2
global e3
global e4
global e5
global totText
global avgText
global gradeText

totText = StringVar()
avgText = StringVar()
gradeText = StringVar()

Label(root, text="Marks1").place(x=10, y=10)


Label(root, text="Marks2").place(x=10, y=40)
Label(root, text="Marks3").place(x=10, y=70)
Label(root, text="Marks4").place(x=10, y=100)
Label(root, text="Marks5").place(x=10, y=130)
Label(root, text="Total:").place(x=10, y=160)
Label(root, text="Avg:").place(x=10, y=190)
Label(root, text="Grade:").place(x=10, y=220)

e1 = Entry(root) e1.place(x=100, y=10)

e2 = Entry(root) e2.place(x=100, y=40)

e3 = Entry(root) e3.place(x=100, y=70)

e4 = Entry(root) e4.place(x=100, y=100)

e5 = Entry(root) e5.place(x=100, y=130)

result = Label(root, text="", textvariable=totText).place(x=100, y=160)


avg = Label(root, text="", textvariable=avgText).place(x=100, y=190)
grade = Label(root, text="", textvariable=gradeText).place(x=100, y=220)
Button(root, text="Result", command=Ok ,height = 1, width = 3).place(x=10,
y=240)
marks1 = Entry(root)

14
marks2 = Entry(root)
marks3 = Entry(root)
marks4 = Entry(root)
marks5 = Entry(root)
root.mainloop()

Python Tkinter Checkbutton:

The Checkbutton is used to track the user's choices provided to the application. In
other words, we can say that Checkbutton is used to implement the on/off selections.

The Checkbutton can contain the text or images. The Checkbutton is mostly used to
provide many choices to the user among which, the user needs to choose the one. It
generally implements many of many selections.

The syntax to use the checkbutton is given below.

Syntax

w = checkbutton(master, options)

SN Option Description

1 activebackground It represents the background color when the checkbutton is under


the cursor.

2 activeforeground It represents the foreground color of the checkbutton when the


checkbutton is under the cursor.

3 bg The background color of the button.

4 bitmap It displays an image (monochrome) on the button.

5 bd The size of the border around the corner.

6 command It is associated with a function to be called when the state of the


checkbutton is changed.

15
7 cursor The mouse pointer will be changed to the cursor name when it is
over the checkbutton.

8 disableforeground It is the color which is used to represent the text of a disabled


checkbutton.

9 font It represents the font of the checkbutton.

10 fg The foreground color (text color) of the checkbutton.

11 height It represents the height of the checkbutton (number of lines). The


default height is 1.

12 highlightcolor The color of the focus highlight when the checkbutton is under
focus.

13 image The image used to represent the checkbutton.

14 justify This specifies the justification of the text if the text contains multiple
lines.

15 offvalue The associated control variable is set to 0 by default if the button is


unchecked. We can change the state of an unchecked variable to
some other one.

16 onvalue The associated control variable is set to 1 by default if the button is


checked. We can change the state of the checked variable to some
other one.

17 padx The horizontal padding of the checkbutton

18 pady The vertical padding of the checkbutton.

19 relief The type of the border of the checkbutton. By default, it is set to


FLAT.

20 selectcolor The color of the checkbutton when it is set. By default, it is red.

21 selectimage The image is shown on the checkbutton when it is set.

22 state It represents the state of the checkbutton. By default, it is set to


normal. We can change it to DISABLED to make the checkbutton
unresponsive. The state of the checkbutton is ACTIVE when it is
under focus.

16
24 underline It represents the index of the character in the text which is to be
underlined. The indexing starts with zero in the text.

25 variable It represents the associated variable that tracks the state of the
checkbutton.

26 width It represents the width of the checkbutton. It is represented in the


number of characters that are represented in the form of texts.

27 wraplength If this option is set to an integer number, the text will be broken into
the number of pieces.

Methods
The methods that can be called with the Checkbuttons are described in the following table.

SN Method Description

1 deselect() It is called to turn off the checkbutton.

2 flash() The checkbutton is flashed between the active and normal colors.

3 invoke() This will invoke the method associated with the checkbutton.

4 select() It is called to turn on the checkbutton.

5 toggle() It is used to toggle between the different Checkbuttons

Example
from tkinter import *
top = Tk()
top.geometry("200x200")
checkvar1 = IntVar()
checkvar2 = IntVar()
checkvar3 = IntVar()
chkbtn1 = Checkbutton(top, text = "C", variable = checkvar1, onvalue = 1, offvalue
= 0, height = 2, width = 10)

17
chkbtn2 = Checkbutton(top, text = "C++", variable = checkvar2, onvalue = 1,
offvalue = 0, height = 2, width = 10)
chkbtn3 = Checkbutton(top, text = "Java", variable = checkvar3, onvalue = 1,
offvalue = 0, height = 2, width = 10)
chkbtn1.pack()
chkbtn2.pack()
chkbtn3.pack()
top.mainloop

Output:

Eg:

import tkinter

window_main = tkinter.Tk(className='Tkinter - TutorialKart', )


window_main.geometry("450x250")

check_1 = tkinter.IntVar()
check_2 = tkinter.IntVar()
check_3 = tkinter.IntVar()

def check1Clicked():
if check_1.get() :
print('Checkbox 1 selected')
else :
print('Checkbox 1 unselected')

def check2Clicked():
if check_2.get() :

18
print('Checkbox 2 selected')
else :
print('Checkbox 2 unselected')

def check3Clicked():
if check_3.get() :
print('Checkbox 3 selected')
else :
print('Checkbox 3 unselected')

check_but_1 = tkinter.Checkbutton(window_main, text = 'Listening to Music', variable = check_1,


onvalue = 1, offvalue = 0, command=check1Clicked)
check_but_1.pack()

check_but_2 = tkinter.Checkbutton(window_main, text = 'Reading Books', variable = check_2,


onvalue = 1, offvalue = 0, command=check2Clicked)
check_but_2.pack()

check_but_3 = tkinter.Checkbutton(window_main, text = 'Watching Movies', variable = check_3,


onvalue = 1, offvalue = 0, command=check3Clicked)
check_but_3.pack()

window_main.mainloop()

Python Tkinter Canvas

The canvas widget is used to add the structured graphics to the python application. It is
used to draw the graph and plots to the python application. The syntax to use the canvas is given
below.

Syntax
w = canvas(parent, options)

A list of possible options is given below.

SN Option Description

1 bd The represents the border width. The default width is 2.

2 bg It represents the background color of the canvas.

19
3 confine It is set to make the canvas unscrollable outside the scroll region.

4 cursor The cursor is used as the arrow, circle, dot, etc. on the canvas.

5 height It represents the size of the canvas in the vertical direction.

6 highlightcolor It represents the highlight color when the widget is focused.

7 relief It represents the type of the border. The possible values are SUNKEN,
RAISED, GROOVE, and RIDGE.

8 scrollregion It represents the coordinates specified as the tuple containing the area
of the canvas.

9 width It represents the width of the canvas.

10 xscrollincrement If it is set to a positive value. The canvas is placed only to the multiple
of this value.

11 xscrollcommand If the canvas is scrollable, this attribute should be the .set() method of
the horizontal scrollbar.

12 yscrollincrement Works like xscrollincrement, but governs vertical movement.

13 yscrollcommand If the canvas is scrollable, this attribute should be the .set() method of
the vertical scrollbar.

Example

from tkinter import *


top = Tk()
top.geometry("200x200")

#creating a simple canvas


c = Canvas(top,bg = "pink",height = "200")
c.pack()
top.mainloop()

20
Output:

Example: Creating an arc


from tkinter import *
top = Tk()
top.geometry("200x200")

#creating a simple canvas


c = Canvas(top,bg = "pink",height = "200",width = 200)
arc = c.create_arc((5,10,150,200),start = 0,extent = 150, fill= "white")
c.pack()
top.mainloop()

Output:

21
Python Tkinter Radiobutton
The Radiobutton widget is used to implement one-of-many selection in the python
application. It shows multiple choices to the user out of which, the user can select only one out of
them. We can associate different methods with each of the radiobutton.

We can display the multiple line text or images on the radiobuttons. To keep track the user's
selection the radiobutton, it is associated with a single variable. Each button displays a single
value for that particular variable.
The syntax to use the Radiobutton is given below.
Syntax
w = Radiobutton(top, options)

SN Option Description

1 activebackground The background color of the widget when it has the focus.

2 activeforeground The font color of the widget text when it has the focus.

3 anchor It represents the exact position of the text within the widget if the
widget contains more space than the requirement of the text. The
default value is CENTER.

4 bg The background color of the widget.

5 bitmap It is used to display the graphics on the widget. It can be set to


any graphical or image object.

6 borderwidth It represents the size of the border.

7 command This option is set to the procedure which must be called every-
time when the state of the radiobutton is changed.

8 cursor The mouse pointer is changed to the specified cursor type. It can
be set to the arrow, dot, etc.

9 font It represents the font type of the widget text.

10 fg The normal foreground color of the widget text.

11 height The vertical dimension of the widget. It is specified as the number


of lines (not pixel).

12 highlightcolor It represents the color of the focus highlight when the widget has
the focus.

22
13 highlightbackground The color of the focus highlight when the widget is not having
the focus.

14 image It can be set to an image object if we want to display an image


on the radiobutton instead the text.

15 justify It represents the justification of the multi-line text. It can be set


to CENTER(default), LEFT, or RIGHT.

16 padx The horizontal padding of the widget.

17 pady The vertical padding of the widget.

18 relief The type of the border. The default value is FLAT.

19 selectcolor The color of the radio button when it is selected.

20 selectimage The image to be displayed on the radiobutton when it is selected.

21 state It represents the state of the radio button. The default state of the
Radiobutton is NORMAL. However, we can set this to DISABLED
to make the radiobutton unresponsive.

22 text The text to be displayed on the radiobutton.

23 textvariable It is of String type that represents the text displayed by the


widget.

24 underline The default value of this option is -1, however, we can set this
option to the number of character which is to be underlined.

25 value The value of each radiobutton is assigned to the control variable


when it is turned on by the user.

26 variable It is the control variable which is used to keep track of the user's
choices. It is shared among all the radiobuttons.

27 width The horizontal dimension of the widget. It is represented as the


number of characters.

28 wraplength We can wrap the text to the number of lines by setting this option
to the desired number so that each line contains only that
number of characters.

23
Methods
The radio button widget provides the following methods.
SN Method Description

1 deselect() It is used to turn of the radiobutton.

2 flash() It is used to flash the radiobutton between its active and normal colors few
times.

3 invoke() It is used to call any procedure associated when the state of a Radiobutton
is changed.

4 select() It is used to select the radiobutton.

Example
from tkinter import *
def selection():
selection = "You selected the option " + str(radio.get())
label.config(text = selection)
top = Tk()
top.geometry("300x150")
radio = IntVar()
lbl = Label(text = "Favourite programming language:")
lbl.pack()
R1 = Radiobutton(top, text="C", variable=radio, value=1,
command=selection)
R1.pack( anchor = W )
R2 = Radiobutton(top, text="C++", variable=radio, value=2,
command=selection)
R2.pack( anchor = W )
R3 = Radiobutton(top, text="Java", variable=radio, value=3,
command=selection)
R3.pack( anchor = W)
label = Label(top)
label.pack()
top.mainloop()

24
Output:

Eg:
import tkinter as tk

# Create the main window


window = tk.Tk()
window.geometry("300x200")
window.title("PythonExamples.org")

# Create a variable to hold the selected option


radio_var = tk.StringVar()

# Create Radiobuttons
radio_button1 = tk.Radiobutton(window, text="Option 1", variable=radio_var, value="Option 1")
radio_button2 = tk.Radiobutton(window, text="Option 2", variable=radio_var, value="Option 2")
radio_button3 = tk.Radiobutton(window, text="Option 3", variable=radio_var, value="Option 3")

# Pack the Radiobuttons


radio_button1.pack()
radio_button2.pack()
radio_button3.pack()

25
def check_if_option_selected():
selected_option = radio_var.get()
if selected_option == "":
print("No option selected.")
else:
print(f"Selected option : {selected_option}")

# Button widget
clear_button = tk.Button(window, text="Check if an Option is Selected",
command=check_if_option_selected)
clear_button.pack()

# Start the Tkinter event loop


window.mainloop()

26

You might also like