UNIT 5 (GUI Programming using Tkinter)
UNIT 5 (GUI Programming using Tkinter)
Introduction
Create a new file in IDLE ,enter the following code, and save it as hello_tkinter.py:
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
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.
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.
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.
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()
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.
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
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).
• 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:
import tkinter as tk
root = tk.Tk()
root.mainloop()
Output:
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:
import tkinter as tk
root = tk.Tk()
root.mainloop()
Output:
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:
import tkinter as tk
root = tk.Tk()
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:
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
root.title("ComboBox Example")
root.geometry('500x200')
Output:
The Checkbutton widget is a labeled checkbox for entering boolean data. The commonly used
arguments to CheckButton are as follows:
Example Code:
import tkinter as tk
root = tk.Tk()
root.title("CheckButton Example")
root.geometry('500x200')
root.mainloop()
Output:
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
Output:
import tkinter as tk
root = tk.Tk()
root.geometry('200x200')
i,j=1,0
Output:
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.
• 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.
Example Code:
import tkinter as tk
root = tk.Tk()
root.title("Text Example")
root.geometry('400x400')
text1 = tk.Text(root)
text1.pack()
root.mainloop()
Output:
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.
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("")
Output:
Calculator Example
import tkinter as tk
Output: