DEV Community

Cover image for GUI in Python Using Tkinter
Anjali Kumawat
Anjali Kumawat

Posted on

GUI in Python Using Tkinter

GUI in Python

Python libraries to create Graphical Interfaces :

  • Tkinter
  • Python QT
  • wxPython
  • Kivy

Tkinter is an inbuilt Python module used to create simple GUI apps.

Tk provides following widgets :

  • button
  • canvas
  • checkbutton
  • Combobox
  • entry
  • frame
  • label
  • labelframe
  • listbox
  • menu
  • menubutton
  • message
  • notebook
  • tk_optionmenu
  • panedwindow
  • progressbar
  • radiobutton
  • scale
  • scrollbar
  • separator
  • sizegrip
  • spinbox
  • text
  • treeview

It provided the following top-level windows :

  • tk_chooseColor
  • tk_chooseDirectory
  • tk_dialog
  • tk_getOpenFile
  • tk_getSaveFile
  • tk_messageBox
  • tk_popup
  • toplevel

Tk also provides three geometry managers :

  • ​ place - It positions widgets at absolute locations
  • ​ grid - It arranges widgets in a grid
  • ​ pack - It packs widgets into a cavity

Basics of tkinter

  1. import tkinter module
  2. create the main window (container)
  3. Add any number of widgets to the main window
  4. Enter the main event loop

Eg.

import tkinter
window = Tkinter.Tk()          # creates main window
window.title("GUI")
label = tkinter.Label(window , text="Hello World !!").pack()
window.mainloop()
Enter fullscreen mode Exit fullscreen mode

mainloop() is used when our application is ready to run. mainloop() is an infinite loop used to run the application, wait for an event to occur and process the event till the window is not closed.

Widgets

Button

It is used to add a button in our application.

window = Button(master, option=value)
Enter fullscreen mode Exit fullscreen mode

master represents the parent window.

activebackground : sets the background color when button is under the cursor.

activeforeground : sets the foreground color when button is under the cursor.

bg : sets normal background color

fg : sets the foreground color

command : to call a function

font : sets the font of button label

image : sets the image on the button

width : sets the width of the button

height : sets the height of the button

justify : LEFT , RIGHT , CENTER

import tkinter as tk
window = tk.Tk()
window.title("Python")
button = tk.Button(window , text = 'GUI',width = 25,command = window.destroy)
button.pack()
window.mainloop()
Enter fullscreen mode Exit fullscreen mode

Output is :

Image description

Label

It is used to display text or image.

window = Label(master,option=value)
Enter fullscreen mode Exit fullscreen mode

bg : sets the normal background color
command : to call a function
font : sets the font of Label text
image : sets the image on the Label
width : sets the width of the Label

height : sets the height of the Label

from tkinter import *
root = Tk()
l1 = Label(root,text="GUI Python",bg="pink",width = 25)
l1.pack()
root.mainloop()

Enter fullscreen mode Exit fullscreen mode

Output is :

Image description

Entry

(Text Field)

It is used to input single line of text.

window = Entry(master,option=value)
Enter fullscreen mode Exit fullscreen mode

bg : sets the background color

fg : sets the foreground color

font : sets the font for widget

justify : LEFT , RIGHT , CENTER

command : to call a function

width : sets the width of widget

height : sets the height of widget

show : Normally, the characters that the user types appear in the entry. To make a .password. entry that echoes each character as (show = "*")

Methods of Entry

delete(start,end) : delete a character or range of characters

get() : returns the text of widget

insert(index,string) : inserts text at the specified index

select_range(start,end) : selects specified range.

select_present() : returns True if there is a selection,false otherwise

from tkinter import *
master = Tk()
l1=Label(master,text='first Name')
l1.grid(row=0)
l2=Label(master,text='Last Name')
l2.grid(row=1)
e1=Entry(master)
e2=Entry(master)
e1.grid(row=0,column=1)
e2.grid(row=1,column=1)
mainloop()
Enter fullscreen mode Exit fullscreen mode

Output is :

Image description

Text

It is used to edit multi line text and formate the way it has to be displayed.

t = Text(master,option = value)
Enter fullscreen mode Exit fullscreen mode

highlightcolor : set the color of focus highlight

insertbackground : set the background of the widget

bg : sets the normal background color

fg : sets the foreground color

bd : sets width of the border around the widget. (Default is 2 pixels)

font : sets the font

image : sets the image

width : sets the width (in pixels)

height : sets the height (in lines)

from tkinter import *
root = Tk()
t = Text(root , height = 4,width=40)
t.pack()
t.insert(END,'ANJALI KUMAWAT \nCOMPUTER SCIENCE UNDERGRAD \nGWOC"21" CONTRIBUTOR')
mainloop()

Enter fullscreen mode Exit fullscreen mode

Output is :

Image description

Methods of Text

delete(start,end) - deletes a specific character or a range of text
get(start,end) - returns a specific character or a range of text
insert(index,string) - inserts text at the specified index

CheckButton

It is used to display a number of options to a user as toggle buttons.

window = CheckButton(master , option = value)
Enter fullscreen mode Exit fullscreen mode

bg : sets background color

fg : sets foreground color

command : to call a function

font : sets the font

image : sets the image

cffvalue : A checkbutton's associated control variable will be set to 0 when it is cleared(off).We can supply an alternate value for the off state.

onvalue : A checkbutton's associated control variable will be set to 1 when it is set(on).We can supply an alternate value for the on state.

state : Default is state=NORMAL but we can use state=DISANLED to grey out the control and make is unresponsive.

variable : This is control variable associated with checkbutton that tracks the current state of widget.Normally this variable is an IntVar and 0 means cleared and 1 means set.

Width : sets the width of widget.

Methods of checkbutton

Deselect() - clears the checkbutton
Select() - selects the checkbutton
Toggle() - reverses the state(on/off)

from tkinter import *
root = Tk()
var1 = IntVar()
var2 = IntVar()
c1 = Checkbutton(root,text = "like Mango ? ",variable = var1,onvalue = 1,offvalue = 0,width = 40)
c2 = Checkbutton(root,text = "like Orange ? ",variable = var2,onvalue = 1,offvalue = 0,width = 40)
c1.pack()
c2.pack()
root.mainloop()
Enter fullscreen mode Exit fullscreen mode

Output is :

Image description

RadioButton

It is used to offer multiple choice option to the used and user can select one option.

window = RadioButton(master,option=value)
Enter fullscreen mode Exit fullscreen mode

bg : sets the background color

fg : sets foreground color

command : to call a function

font : sets the font

image : sets the image

width : sets the width

variable : variable associated with the Radiobuttons.

value : when a radiobutton is selected by user,its control variable is set to its associated value. If the control variable is an IntVar , give each radiobutton in the group a different integer value option. If the control variable is a StringVar,give each radiobutton a different string value option.

Methods of Radiobutton

select() - selects Radiobutton
deselect() - deselects Radiobutton

from tkinter import *

def select():
    if choice.get()==1:
        order = "Large Pizza"
    elif choice.get()==2:
        order = "Medium Pizza"
    else:
        order = "Small Pizza"
    selection = "You have ordered "+order
    label.config(text=selection)

root = Tk()
root.title("Pizza Corner")
choice = IntVar()
rbLarge = Radiobutton(root, text = "Large Pizza",font=20,variable=choice,value=1,command=select)
rbMedium = Radiobutton(root, text = "Medium Pizza",font=20,variable=choice,value=2,command=select)
rbSmall = Radiobutton(root, text = "Small Pizza",font=20,variable=choice,value=3,command=select)
rbLarge.pack(anchor=W)
rbMedium.pack(anchor=W)
rbSmall.pack(anchor=W)
label = Label(root,text="Choose pizza that you want!!",font=35)
label.pack()
mainloop()
Enter fullscreen mode Exit fullscreen mode

Output is :

When we are not clicking on any RadioButton -

Image description

If we are clicking on any RadioButton then -

Image description

SpinBox

It is used to select a value from fixed number of values.

window = Spinbox(root,option=value)
Enter fullscreen mode Exit fullscreen mode

bg : sets the background color

fg : sets foreground color

font : sets the font

justify : LEFT,RIGHT,CENTER

width : sets the width for widget

from_ : sets the minimum value

to : sets the maximum value

Methods for Spinbox

get() - returns the value

from tkinter import *

def select():
    string = "Selection is "+str(sp.get())
    l.config(text=string)

root = Tk()
sp = Spinbox(root,from_=0,to=10,command=select,width = 15,font=30)
sp.pack()
l=Label(root,text=" ")
l.pack()
mainloop()

Enter fullscreen mode Exit fullscreen mode

​Output is :

Image description

Keep Learning......
Keep Coding......πŸ‘©β€πŸ’»β€οΈπŸ™Œ

Top comments (15)

Collapse
 
bitsheriff profile image
bitSheriff

Great introduction :)
I considered tkinter for my project as well but I went with Qt.
As a noob in ui/ux its very easy to use the QtDesigner but to be honest it has some flaws for python programming because it is mainly used for the C++ editor.

But tkinter is definitely interesting, is it possible to load different style sheets too?

Collapse
 
viroxic profile image
Yassine

I like QT too.
It's the best out there i guess.
I think python is more of a processing language than UI.
I think i will go back using c++ for a while. I miss the days.

Collapse
 
anjalikumawat2002 profile image
Anjali Kumawat

Yes in tkinter we can create different styles sheets.πŸ˜€

Collapse
 
krraghav profile image
Raghav kumar

Amazing one✨ keep it up!

Collapse
 
anjalikumawat2002 profile image
Anjali Kumawat

Thank you Raghav🌝

Collapse
 
tapish1511 profile image
Tapish1511

Very well explained πŸ€©πŸ€©πŸ‘πŸ‘

Collapse
 
anjalikumawat2002 profile image
Anjali Kumawat

Thankyou ✨

Collapse
 
archijain profile image
archi-jain

This is my first time reading about GUI in python, I like the explaination and now I'm curious to learn more... thanks for sharing anjaliii

Collapse
 
anjalikumawat2002 profile image
Anjali Kumawat

Thanks a lot archiiπŸŒπŸ™Œ

Collapse
 
khush2706 profile image
Khushboo Chaturvedi

Very well researched. Great job🀩

Collapse
 
anjalikumawat2002 profile image
Anjali Kumawat

Thank you❀

Collapse
 
david050708 profile image
david050708

Super Explanation I like it

Collapse
 
anjalikumawat2002 profile image
Anjali Kumawat

ThankYouπŸ™Œ

Collapse
 
mhadi2003 profile image
Mahdi

That's great πŸ‘ŒπŸ‘Œ

Collapse
 
anjalikumawat2002 profile image
Anjali Kumawat

Thanks