0% found this document useful (0 votes)
14 views

UNIT 5 (GUI Programming using Tkinter)

Tkinter is a Python interface for creating GUI applications, included in the standard library. The document provides examples of basic Tkinter applications, including a Hello World program, and explains various widgets such as Entry, Spinbox, Listbox, Combobox, Checkbutton, Radiobutton, and Text, along with their properties and methods. It also discusses how to arrange these widgets and their usage in data-driven applications.

Uploaded by

materialstudy072
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

UNIT 5 (GUI Programming using Tkinter)

Tkinter is a Python interface for creating GUI applications, included in the standard library. The document provides examples of basic Tkinter applications, including a Hello World program, and explains various widgets such as Entry, Spinbox, Listbox, Combobox, Checkbutton, Radiobutton, and Text, along with their properties and methods. It also discusses how to arrange these widgets and their usage in data-driven applications.

Uploaded by

materialstudy072
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

GUI Programming using Tkinter

Introduction

• Tkinter is a Python interface to the Tk GUI library, suitable for data-driven


applications, simple utilities, configuration dialogs, and other business logic
applications.
• Tkinter is included in the Python standard library so it is not required to install it
separately.
• IDLE is written in Python using Tkinter, and it provides us with not only an editing
environment for Python, but also a great example of Tkinter in action.

Creating a Tkinter Hello World

Create a new file in IDLE ,enter the following code, and save it as hello_tkinter.py:

'''Hello World Application for Tkinter'''

from tkinter import *

def on_change():
print("Button Clicked")

root = Tk()
label1 = Label(root, text="Hello World!!")
label2 = Label(root, text="This is GUI using Python.")
button = Button(root, text="Clear", command=on_change)
label3 = Label(root, text="Enter your Name: ")
entry = Entry(root)
label1.pack()
label2.pack()
button.pack()
label3.pack()
entry.pack()
root.mainloop()

After running this code, the output will be a small window having all the components (widgets):
Meaning of lines written in Code

from tkinter import *

This imports the Tkinter library into the global namespace. This isn't best practice,
because it fills your namespace with a lot of classes, which you might accidentally
overwrite, but it's okay for very small scripts.

root = Tk()

This creates root or master application object. This represents the primary top-level
window and main execution thread of the application, so there should be one and only
one instance of Tk for every application.

label = Label(root, text="Hello World")

This creates a new Label object. As the name implies, a Label object is just a widget
for displaying text (or images). The first argument we pass to Label( ) is the parent or
master widget. Tkinter widgets are arranged in a hierarchy starting with the root
window, each widget being contained by another. Any time you create a widget, your
first argument will be the widget object that contains the new widget. In this case, we're
placing our Label object on the main application window. The second argument is a
keyword argument that specifies the text to be displayed on the Label object.

label.pack( )/button.pack( )/entry.pack( )

This places the new label/button/textbox widget onto its parent widget using pack()
method.

root.mainloop( )

This line starts the main event loop. This loop is responsible for processing all the
events—keystrokes, mouse clicks, and so on—and it will run until the program is quit.
This is usually the last line of any Tkinter script, since any code after it won't run until
the main window is closed.

Another way of writing the code:

'''Hello World Application for Tkinter'''

import tkinter as tk

def on_change():
print("Button Clicked")

root = tk.Tk()
label1 = tk.Label(root, text="Hello World!!")
label2 = tk.Label(root, text="This is GUI using Python.")
button = tk.Button(root, text="Clear", command=on_change)
label3 = tk.Label(root, text="Enter your Name: ")
entry = tk.Entry(root)
label1.pack()
label2.pack()
button.pack()
label3.pack()
entry.pack()
root.mainloop()

Exploring Tkinter input widgets

Tkinter offers a variety of input widgets for different kinds of data. However, ttk offers
additional widget types and enhances some of Tkinter's native widgets. The following table
offers advice on which widgets are most appropriate for different kinds of data entry.

Widget Description Used for


Entry Basic text entry Single-line strings
Spinbox Text entry with Numbers
increment/decrement arrows
Listbox Box with a list of choices Choice between several
values
OptionMenu Drop-down list with choices Choice between several
values
Combobox Drop-down list with optional Choice between several
text entry values plus text entry
Checkbutton Checkbox with label Boolean values
Radiobutton Like checkbox, but only one of a Choice between small set
set can be selected of values
Text Multiline text entry box Long, multiline strings
Scale Mouse-operated slider Bounded number data

To group the preceding fields in Tkinter, we could just insert labels between each set of fields,
but there are various options for grouping widgets together:

Widget Description
LabelFrame Frame with label text and an optional border
NoteBook Tabbed widget that allows multiple pages
PanedWindow Allows for multiple re-sizable frames in
horizontal or vertical arrangement

Exploring Tkinter widgets

The Entry widget

The Entry widget is a basic, one-line character entry. The commonly used arguments to Entry
are as follows:

• parent: This argument sets the parent widget for the entry.
• bg: This argument sets the background color of the entry widget.
• bd: This argument sets the size of the border around the label. Default value is 2 pixels.
• font: This argument sets the font of the text that will be displayed in the entry.
• fg: This argument sets the color of the text that will be displayed in the entry.
• justify: If text contains multiple lines, this argument sets the alignment of the text.
Values are center, left or right.
• textvariable: This is a Tkinter StringVar variable whose value will be bound to this
input widget.
• show: This argument determines which character will be displayed when you type into
the box. By default, it's the character you type, but this can be replaced (for example,
for password entry you might specify * or dot to be shown instead).

Methods used with Entry Widget:

• get(): reads and return the text (as string) entered in the entry widget.
• delete(): deletes the characters from the widgets.
• insert(index, ‘name’): insert the string specified as ‘name’ before the character at the
given index.

Example Code:

'''Tkinter Entry Widget Example'''

import tkinter as tk

root = tk.Tk()

label1 = tk.Label(root, text="Username").grid(row=0, column=0)


label2 = tk.Label(root, text="Password").grid(row=1, column=0)
txtbox1 = tk.Entry(root, bg="yellow",font="Cambria").grid(row=0, column=1)
txtbox2 = tk.Entry(root, bd=4, fg="red", show="*").grid(row=1, column=1)

root.mainloop()

Output:

The Spinbox widget

The Spinbox widget adds increment and decrement buttons to a regular Entry widget, making
it suitable for numerical data. The commonly used arguments to SpinBox are as follows:
• parent: This argument sets the parent widget for the spinbox.
• bg: This argument sets the background color of the spinbox.
• bd: This argument sets the size of the border around the spinbox. Default value is 2
pixels.
• font: This argument sets the font of the text that will be displayed in the spinbox.
• fg: This argument sets the color of the text that will be displayed in the spinbox.
• justify: If text contains multiple lines, this argument sets the alignment of the text.
Values are center, left or right.
• textvariable: This is a Tkinter StringVar variable whose value will be bound to this
input widget.
• from_: This argument determines the lowest value to which the arrows decrement.
• to: This argument determines the highest value to which the arrows increment.
• increment: This argument represents the amount at which arrows increment or
decrement.
• values: This argument takes a list of string or number values that can be incremented
through.

The Spinbox widget is not just for numbers, it can also take a list of strings, which can be
selected using the arrow buttons. Because it can be used for strings or numbers, the textvariable
argument takes the StringVar, IntVar, or DoubleVar data types.

Example Code:

'''Tkinter Spinbox Widget Example'''

import tkinter as tk

root = tk.Tk()

label1 = tk.Label(root, text="Select the Number of Subjects").grid(row=0, column=0)


label2 = tk.Label(root, text="Select the Number of Books").grid(row=1, column=0)
sbox1 = tk.Spinbox(root, from_=1, to=5, increment=1).grid(row=0, column=1)
sbox2 = tk.Spinbox(root, from_=1, to=10, increment=1).grid(row=1, column=1)

root.mainloop()

Output:

The ListBox Widget

The Listbox is used to display the list of items. All the items should have same type of font and
font color. The commonly used arguments to ListBox are as follows:
• parent: This argument sets the parent widget for the spinbox.
• bg: This argument sets the background color of the listbox.
• bd: This argument sets the size of the border around the listbox. Default value is 2
pixels.
• font: This argument sets the font of the text that will be displayed in the listbox.
• fg: This argument sets the color of the text that will be displayed in the listbox.
• height: This argument sets the height of the listbox widget.
• width: This argument sets the width of the listbox widget.
• textvariable: This is a Tkinter StringVar variable whose value will be bound to this
input widget.
• yscrollcommand: This argument is used for scrolling vertically.
• xscrollcommand: This argument is used for scrolling horizontally.

Example Code:

'''Tkinter ListBox Example'''

import tkinter as tk

root = tk.Tk()

label1 = tk.Label(root, text="Select the City").grid(row=0, column=0)


list1 = tk.Listbox(root, height=6, width=10, bg="grey", fg="yellow")
list1.insert(1, "Delhi")
list1.insert(2, "Ghaziabad")
list1.insert(3, "Gurugram")
list1.insert(4, "Noida")
list1.insert(5, "Greater Noida")
list1.grid(row=0, column=1)
label2 = tk.Label(root, text="Select the Food").grid(row=1, column=0)
list2 = tk.Listbox(root, height=6, width=10, bg="grey", fg="yellow")
list2.insert(1, "Food Item 1")
list2.insert(2, "Food Item 2")
list2.insert(3, "Food Item 3")
list2.insert(4, "Food Item 4")
list2.insert(5, "Food Item 5")
list2.grid(row=2, column=1)

root.mainloop()

Output:
The Combobox widget

The Combobox is an Entry widget that adds a drop-down select menu. To populate the drop-
down menu, simply pass in a values argument with a list of the strings, which the user can
select.

The Combobox is defined in ttk library. The commonly used arguments to ComboBox are as
follows:

• parent: This argument sets the parent widget for the Combobox.
• width: This argument sets the width of the Combobox.
• height: This argument sets the height of the Combobox.
• values: This argument defines the values that will be displayed in the ComboBox.

Example Code:

'''Tkinter ComboBox Widget Example'''

import tkinter as tk
from tkinter import ttk

root = tk.Tk()
root.title("ComboBox Example")
root.geometry('500x200')

label1 = tk.Label(root, text="Select the Subject").grid(row=0, column=0)


combo1 = ttk.Combobox(root, values=["DSTL", "Python", "DS", "WDW"]).grid(row=0,
column=1)
root.mainloop()

Output:

The Checkbutton widget

The Checkbutton widget is a labeled checkbox for entering boolean data. The commonly used
arguments to CheckButton are as follows:

• text: This argument sets the label for the widget.


• variable: This argument is BooleanVar, to which the checked status is bound.
• textvariable: This argument can be used to bind a variable to the label text of the
widget.

Example Code:

'''Tkinter CheckButton Widget Example'''

import tkinter as tk

root = tk.Tk()
root.title("CheckButton Example")
root.geometry('500x200')

check1 = tk.Checkbutton(root, text="I accept the Terms and Conditions").pack()

root.mainloop()

Output:

The Checkbox widget appears as a clickable box with a label by it


The Radiobutton Widget

The RadioButton is a Tkinter widget that provides list of options, however, user can select only
one option (at a time) out of the available options. Radio buttons can be displayed in the form
of button box also. To display it as button box, the indicator option should be set as 0 (zero).

Example Code:

import tkinter as tk

values = {"Male":1, "Female":2}


root = tk.Tk()
label = tk.Label(root, text="Select your gender")
label.pack()
for (text, value) in values.items():
tk.Radiobutton(root, text = text, value = value).pack()
root.mainloop()

Output:

Arranging Radio Buttons in one line

import tkinter as tk

root = tk.Tk()
root.geometry('200x200')

values = {"Male":1, "Female":2}

label = tk.Label(root, text="Select your gender").grid(row=0, column=0)

i,j=1,0

for (text, value) in values.items():


tk.Radiobutton(root, text = text, value = value).grid(row=i, column=j)
j+=1
root.mainloop()

Output:

The Text widget

The Text widget is much more than just a multiline Entry widget. It has a powerful tagging
system that allows user to implement multi-coloured text, hyperlink-style clickable text, and
more. Unlike other widgets, it can't be bound to a Tkinter StringVar, so setting or retrieving its
contents needs to be done through its get(), insert(), and delete() methods.
When reading or modifying with these methods, user is required to pass in one or two index
values to select the character or range of characters that user is operating on. These index values
are strings that can take any of the following formats:

The line number and character number separated by a dot: Lines are numbered from 1
and characters from 0, so the first character on the first line is 1.0, while the twelfth character
on the fourth line would be 4.11. The end string or Tkinter constant END, indicating the end
of the field.

A numerical index plus one of the words linestart, lineend, wordstart, and wordend,
indicating the start or end of the line or word relative to the numerical index. For example, 6.2
wordstart would be the start of the word containing the third character on line 6; 2.0 lineend
would be the end of line 2.

Any of the preceding, a plus or minus operator, and a number of characters or lines. For
example, 2.5 wordend - 1 chars would be the character before the end of the word containing
the sixth character on line 2.

The commonly used arguments to Text widget are as follows:

• parent: This argument sets the parent widget for the Text.
• bg: This argument sets the background color of the Text.
• bd: This argument sets the size of the border around the Text. Default value is 2 pixels.
• font: This argument sets the font of the text that will be displayed in the Text.
• fg: This argument sets the color of the text that will be displayed in the Text.
• height: This argument sets the height of the Text widget.
• width: This argument sets the width of the Text widget.
• yscrollcommand: This argument is used for scrolling vertically.
• xscrollcommand: This argument is used for scrolling horizontally.

Methods used with Text Widget:

• insert(index, string): inserts a string at a specified index.


• get(startindex, endindex): to get characters within specified range.
• delete(startindex, endindex): delete characters within specified range.

Example Code:

import tkinter as tk

root = tk.Tk()
root.title("Text Example")
root.geometry('400x400')

text1 = tk.Text(root)

# Inserting a string at the beginning


text1.insert('1.0', 'This is a text widget!')

# Inserting a string into the current text widget


text1.insert('1.10', 'multiline ')

# Get the whole string


text1.get('1.0', tk.END)

# Delete the last character (!)


text1.delete('end - 2 chars')

text1.pack()

root.mainloop()

Output:

The Button widget

The Button widget is a button that user click with the mouse or spacebar. Just like the
Checkbutton widget, this widget uses the text and textvariable configuration options to control
the label on the button. The Button take a command argument, which specifies a Python
function to run when the button is clicked.

The following example shows the use of a Button:

from tkinter import *


from tkinter.ttk import *
def text_update(x):
text.delete(0, END)
text.insert(0, x)

def swaptext():
return text_update("Welcome")

root = Tk()
root.title("Button Test")
root.geometry('400x400')
label = Label(root, text="Click the button to see the text")
text = Entry(root)
my_button = Button(root, text="Click Me", command=swaptext)
label.pack()
text.pack()
my_button.pack()
root.mainloop()

Example 2:

import tkinter as tk

root = tk.Tk()
root.title("Button Test")
root.geometry('400x400')
txt = ""

def displaytext(t):
global txt
txt = t
x.set(txt)

def clear_field():
global txt
txt = ""
x.set("")

label = tk.Label(root, text="Click the button to see the text")


x = tk.StringVar()
text = tk.Entry(root, textvariable=x)
button1 = tk.Button(root, text="Welcome", command = lambda: displaytext("welcome"))
button2 = tk.Button(root, text="Hello", command = lambda: displaytext("hello"))
button3 = tk.Button(root, text="Clear", command = lambda: clear_field())
label.pack()
text.pack()
button1.pack()
button2.pack()
button3.pack()
root.mainloop()

Output:

On clicking the “welcome” button:

On clicking the “hello” button:


On clicking the “clear” button:

Calculator Example

import tkinter as tk

# Creating the parent window


root = tk.Tk()
root.title("Simple Calculator")

# Variable to store the current result


result = ""

# Function to update the result variable


def update(num):
global result
result += str(num)
value.set(result)

# Function to evaluate the result


def evaluate():
global result
result = eval(result)
value.set(result)
result = str(result)

# Function to clear the result


def clear():
global result
result = ""
value.set("")

# Creating entry widget for displaying the equation


value = tk.StringVar()
text1 = tk.Entry(root, textvariable=value, width=20)
text1.grid(row=0, column=0, columnspan=4)

'''Lambda expressions are used here to create anonymous functions


that can be defined inline within a larger expression.
They are used here to pass arguments to the update function
when a button is clicked.'''

# Creating buttons for digits (0 to 9)


one = tk.Button(root, text="1", command=lambda: update(1))
one.grid(row=1, column=0)
two = tk.Button(root, text="2", command=lambda: update(2))
two.grid(row=1, column=1)
three = tk.Button(root, text="3", command=lambda: update(3))
three.grid(row=1, column=2)

four = tk.Button(root, text="4", command=lambda: update(4))


four.grid(row=2, column=0)
five = tk.Button(root, text="5", command=lambda: update(5))
five.grid(row=2, column=1)
six = tk.Button(root, text="6", command=lambda: update(6))
six.grid(row=2, column=2)

seven = tk.Button(root, text="7", command=lambda: update(7))


seven.grid(row=3, column=0)
eight = tk.Button(root, text="8", command=lambda: update(8))
eight.grid(row=3, column=1)
nine = tk.Button(root, text="9", command=lambda: update(9))
nine.grid(row=3, column=2)

zero = tk.Button(root, text="0", command=lambda: update(0))


zero.grid(row=4, column=1)

# Create the operator buttons


add = tk.Button(root, text="+", command=lambda: update("+"))
add.grid(row=1, column=3)
subtract = tk.Button(root, text="-", command=lambda: update("-"))
subtract.grid(row=2, column=3)
multiply = tk.Button(root, text="*", command=lambda: update("*"))
multiply.grid(row=3, column=3)
divide = tk.Button(root, text="/", command=lambda: update("/"))
divide.grid(row=4, column=3)

equals = tk.Button(root, text="=", command=evaluate)


equals.grid(row=4, column=2)
clear = tk.Button(root, text="C", command=clear)
clear.grid(row=4, column=0)

# Start the main loop


root.mainloop()

Output:

You might also like