12. Python GUI

Introduction

Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, tkinter is most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python.

Python with tkinter outputs the fastest and easiest way to create the GUI applications. Creating a GUI using tkinter is an easy task.

What is Tkinter

Tkinter is an inbuilt Python module used to create simple GUI apps. It is the most commonly used module for GUI apps in the Python.You don't need to worry about installation of the Tkinter module as it comes with Python default. Tkinter is a Python interface to the Tk graphics library. Tk is a graphics library widely used and available everywhere. 

Tkinter is an open source, portable graphical user interface (GUI) library designed for use in Python scripts. Tkinter relies on the Tk library, the GUI library used by Tcl/Tk and Perl, which is in turn implemented in C. Thus, Tkinter is implemented using multiple layers

Tkinter is included with Python as a library. To use it:

from Tkinter import *

create a tkinter:

What can I do with Tkinter?

Create First Hello Program

import tkinter

window = tkinter.Tk()

# to rename the title of the window

window.title("Welcome to Tkinter")

# pack is used to show the object in the window

label = tkinter.Label(window, text = "Hello World!").pack()

window.mainloop()

Output:

When you run this program this will open a new window and display text Hello World!

Tkinter Widgets

Widgets are something like elements in the HTML. You will find different types of widgets to the different types of elements in Tkinter.A widget is therefore a graphical object that is available from the Tkinter library. It is a kind of graphical building block. Intuitively, widgets are implemented as classes in Tkinter.

Each widget therefore has a constructor, a destructor, its own set of properties and methods, and so on. While most other GUI toolkits have a very complex widget hierarchy, Tkinter’s hierarchy is extremely simple. All widgets (like Button, Checkbutton, etc.) are derived from the Widget class. All widget subclasses occupy the same level in the hierarchy tree.

Currently there are 19 types of widgets. These are:

Geometry Management

All widgets in the tkinter will have some geometry measurements. These measurements give you to organize the widgets and their parent frames, windows, etc..

Tkinter has the following three Geometry Manager classes.

Command Handlers

A callback is the name of the function that is to be run in response to an event

Callbacks can be defined as a free standing function in our program or as a class member.

use the 'command=' keyword followed by the command you want executed.

For Example:

from tkinter import *

window = Tk()

window.title("Welcome to Tkinter")

Button (window, text='Click Me', command=window.quit).pack(side=LEFT)

window.mainloop()

# command=window.quit # it says, whenever someone clicks the button, call the window.quit function which will exit from the screen

Organizing Layout And Widgets

To arrange the layout in the window, we will use Frame, class. Let's create a simple program to see how the Frame works

Note:- The parameter of any widget method must be where to place the widget. In the below code, we use to place in the window, top_frame, bottom_frame.

import tkinter

window = tkinter.Tk()

window.title("Welcome Tkinter")

# creating 2 frames TOP and BOTTOM

top_frame = tkinter.Frame(window).pack()

bottom_frame = tkinter.Frame(window).pack(side = "bottom")

# now, create some widgets in the top_frame and bottom_frame

btn1 = tkinter.Button(top_frame, text = "Button1", fg = "red").pack()

# 'fg - foreground' is used to color the contents

btn2 = tkinter.Button(top_frame, text = "Button2", fg = "green").pack()# 'text' is used to write the text on the Button

btn3 = tkinter.Button(bottom_frame, text = "Button2", fg = "purple").pack(side = "left")# 'side' is used to align the widgets

btn4 = tkinter.Button(bottom_frame, text = "Button2", fg = "orange").pack(side = "left")

window.mainloop()

output:

When you run this program it will create four button in open windows with different text colors inside button

Grid Layout

Grid is another way to organize the widgets. It uses the Matrix row column concepts. Something like this. see the below example to get an idea of how it works.

import tkinter

window = tkinter.Tk()

window.title("Welcome Tkinter")

# creating 2 text labels and input labels

tkinter.Label(window, text = "Username").grid(row = 0) # this is placed in 0 0

# 'Entry' is used to display the input-field

tkinter.Entry(window).grid(row = 0, column = 1) # this is placed in 0 1

tkinter.Label(window, text = "Password").grid(row = 1) # this is placed in 1 0

tkinter.Entry(window).grid(row = 1, column = 1) # this is placed in 1 1

# 'Checkbutton' is used to create the check buttons

tkinter.Checkbutton(window, text = "Keep Me Logged In").grid(columnspan = 2) # 'columnspan' tells to take the width of 2 columns

# you can also use 'rowspan' in the similar manner

window.mainloop()

Output

when you run this program you will get.

Mouse Clicking Events

Clicking events are of 3 different types namely leftClick, middleClick, and rightClick.

Let us see how to call a particular function based on the event that occurs.

import tkinter

window = tkinter.Tk()

window.title("Welcome Tkinter")

#creating 3 different functions for 3 events

def left_click(event):

     tkinter.Label(window, text = "Left Click!").pack()

def middle_click(event):

     tkinter.Label(window, text = "Middle Click!").pack()

def right_click(event):

     tkinter.Label(window, text = "Right Click!").pack()

window.bind("<Button-1>", left_click)

window.bind("<Button-2>", middle_click)

window.bind("<Button-3>", right_click)

window.mainloop()

Output:

If you run the above program, you will see a blank window. Now, click the left, middle and rightbutton to call respective functions.

Classes

Classes is handy when you're developing a large software or something that's big.Let's see how we use Classes in the GUI apps.

import tkinter

class CreateButton:

    def __init__(self, window):

        self.text_btn = tkinter.Button(window, text = "Click Me!", command = self.say_hi) # create a button to call a function called 'say_hi'

        self.text_btn.pack()

        self.close_btn = tkinter.Button(window, text = "Close", command = window.quit) # closing the 'window' when you click the button

        self.close_btn.pack()

    def say_hi(self):

        tkinter.Label(window, text = "Hi").pack()   

window = tkinter.Tk()

window.title("Welcome Tkinter")

create_btn = CreateButton(window)

window.mainloop()

Drop Down Menus

Steps to create drop down menus are:

For Example:

import tkinter

window = tkinter.Tk()

window.title("Menus")

def function():

     pass

# creating a root menu to insert all the sub menus

root_menu = tkinter.Menu(window)

window.config(menu = root_menu)

# creating sub menus in the root menu

file_menu = tkinter.Menu(root_menu) # it intializes a new sub menu in the root menu

root_menu.add_cascade(label = "Home", menu = file_menu) # it creates the name of the sub menu

file_menu.add_command(label = "Sub Menu one", command = function) # it adds a option to the sub menu 'command' parameter is used to do some action

file_menu.add_command(label = "Sub Menu two", command = function)

file_menu.add_separator() # it adds a line after the 'Open files' option

file_menu.add_command(label = "Exit", command = window.quit)

# creating another sub menu

edit_menu = tkinter.Menu(root_menu)

root_menu.add_cascade(label = "Edit", menu = edit_menu)

edit_menu.add_command(label = "Undo", command = function)

edit_menu.add_command(label = "Redo", command = function)

window.mainloop()

Alert Box

We can create alert boxes in the tkinter using messagebox method. We can also create questions using the message box method.

For Example:

import tkinter

import tkinter.messagebox

window = tkinter.Tk()

window.title("GUI")

# creating a simple alert box

tkinter.messagebox.showinfo("Alert Message", "This is just an alert message!")

# creating a question to get the response from the user [Yes or No Question]

response = tkinter.messagebox.askquestion("Simple Question", "Do you love Python?")

# If user clicks 'Yes' then it returns 1 else it returns 0

if response == 'yes':

     tkinter.Label(window, text = "You love Python!").pack()

else:

     tkinter.Label(window, text = "You don't love Python!").pack()

window.mainloop()

Shapes

We can also create shapes using Python GUI. Let us see how to create shapes using Canvas Widget provided by tkinter in GUI.

For Example:

import tkinter

window = tkinter.Tk()

window.title("Welcome Tkinter")

# creating the 'Canvas' area of width and height 500px

canvas = tkinter.Canvas(window, width = 500, height = 500)

canvas.pack()

# 'create_rectangle' is used to create rectangle. Parameters:- (starting x-point, starting y-point, width, height, fill)

# starting point the coordinates of top-left point of rectangle

rect = canvas.create_rectangle(500, 25, 175, 75, fill = "green")

# you 'delete' shapes using delete method passing the name of the variable as parameter.

#canvas.delete(line1)

# you 'delete' all the shapes by passing 'ALL' as parameter to the 'delete' method

# canvas.delete(tkinter.ALL)

window.mainloop()

Images And Icons

we can also add Images and Icons using PhotoImage method.

For Example:

import tkinter

window = tkinter.Tk()

window.title("GUI")

# taking image from the directory and storing the source in a variable

icon = tkinter.PhotoImage(file = "images/download.png")

# displaying the picture using a 'Label' by passing the 'picture' variable to 'image' parameter

label = tkinter.Label(window, image = icon)

label.pack()

window.mainloop()

Frame Widget

For Example:

from tkinter import *

root= Tk()

frame = Frame(root)

frame.pack()

bottomframe = Frame(root)

bottomframe.pack( side = BOTTOM )

redbutton = Button(frame, text="Red", fg="red")

redbutton.pack( side = LEFT)

greenbutton = Button(frame, text="Brown", fg="brown")

greenbutton.pack( side = LEFT )

bluebutton = Button(frame, text="Blue", fg="blue")

bluebutton.pack( side = LEFT )

blackbutton = Button(bottomframe, text="Black", fg="black")

blackbutton.pack( side = BOTTOM)

root.mainloop()

Checkbutton and RadioButtons

Example of Checkbutton

from tkinter import *

def cb():

    print("variable is", var.get())

win = Tk()

var = IntVar()

c = Checkbutton(win, text="Enable Tab",variable=var,command= (lambda: cb()))

c.pack()

mainloop()

Example of Radio Button

from tkinter import *

def sel():

    selection = "You selected the option " + str(var.get())

    label.config(text = selection)

    root = Tk()

    var = IntVar()

R1 = Radiobutton(root, text="Option 1", variable=var, value=1, command=sel)

R1.pack( anchor = W )

R2 = Radiobutton(root, text="Option 2", variable=var, value=2, command=sel)

R2.pack( anchor = W )

R3 = Radiobutton(root, text="Option 3", variable=var, value=3, command=sel)

R3.pack( anchor = W)

label = Label(root)

label.pack()

root.mainloop()

Sliders

For Example:

from tkinter import *

master = Tk()

w = Scale(master, from_=0, to=42)

w.pack()

w = Scale(master, from_=0, to=200, orient=HORIZONTAL)

w.pack()

mainloop()

ListBox

For Example:

from tkinter import *

master = Tk()

listbox = Listbox(master)

listbox.pack()

listbox.insert(END, "a list entry")

for item in ["one", "two", "three", "four"]:

     listbox.insert(END, item)

mainloop()

Scrollbar

For Example:

from tkinter import *

master = Tk()

scrollbar = Scrollbar(master)

scrollbar.pack(side=RIGHT, fill=Y)

listbox = Listbox(master, yscrollcommand=scrollbar.set)

for i in range(1000):

    listbox.insert(END, str(i))

    listbox.pack(side=LEFT, fill=BOTH)

    scrollbar.config(command=listbox.yview)

mainloop()

Entry Widget

used to enter or display a single line of text. To enter multiple lines of text, use the Text widget

For Example:

from tkinter import *

master = Tk()

e = Entry(master)

e.pack()

def callback():

    print(e.get())

    b = Button(master, text="get", width=10, command=callback)

    b.pack()

mainloop()

Message Widget

The Message widget is used to display text. This is a widget not a text window. Use for on screen instructions or to make a custom message window

For Example:

from tkinter import *

master =Tk()

msg = Message(master, text='This is a Simple Text Message to display')

msg.config(font=('times',14))

msg.pack()

mainloop()