How to Use Tkinter in Python

Introduction

Python has several modules for developing Graphical User Interface(GUI). Talking about those frameworks Turtle, Tkinter, PyQt, and Kivy are some methods of developing a Graphical User Interface(GUI).

In this tutorial, we’re going to take a close look at the Tkinter module. It is one of the tools for developing a Graphical User Interface(GUI). It is an easy and fast method for developing any desktop application.

Turtle, PyQt, and Kivy are some other methods of developing GUI. The steps for developing a GUI application with the Tkinter are as follows:

  • Import the module
  • Create a window
  • Add required widgets
  • Call an event loop to place the action on the user’s screen
from tkinter import *

#Creating window
root = Tk()
#Give a title to window
root.title("CF")
#calling event loop
root.mainloop()

 

Geometry Management in Tkinter

Tkinter provides some of the methods for managing the geometry of the GUI application i.e to place the widgets in the desired location by the developer as per requirement. The methods  for geometry management are

  • Pack – pack() places the widget in the block
  • Grid – grid() places the widget in a table-like structure
  • Place – place() used to place the widget in a specific position

 

Widgets in Tkinter

Label

Label implements a box that displays the image and text.

from tkinter import *

#Creating window
root = Tk()
#Give a title to window
root.title("CF")

l1 = Label(root, text = "CodeFires - Tkinter")
l1.pack()

l2 = Label("GUI with tkinter")
l2.pack()

#calling event loop
root.mainloop()

Output

label tkinter

 

This label is with other widgets for referencing the particular widget.

Button

This widget displays a button on any GUI application

from tkinter import *
#Creating window
root = Tk()
#Give a title to window
root.title("CF")

b1 = Button(root, text = "Button1", fg = "Red").grid(row = 0, column = 0)
b2 = Button(root, text = "Button2", fg = 'Green').grid(row = 0, column = 1)
b3 = Button(root, text = "Button3", fg = "Blue").grid(row = 1, column = 0)
b4 = Button(root, text = "Button4", fg  = "White").grid(row = 1, column = 1)

#calling event loop
root.mainloop()

Output

button in tkinter

 

This is how we create buttons with Tkinter. The above button is not able to perform any task till now. To make those buttons perform a certain task, we need to create a function

from tkinter import *

#Creating window
root = Tk()
#Give a title to window
root.title("CF")
def fun():
    l1 = Label(root, text = "I'm Clicked")
    l1.pack()
    
b1 = Button(root, text = "click", command = fun)
b1.pack()
#calling event loop
root.mainloop()

when the user clicks a button, the fun() function creates a label and displays the text “I’m clicked”. Every time button is clicked, the text “I’m clicked” appears in the window.

 

Entry

This widget is used for creating an entry field in an application

from tkinter import *

#Creating window
root = Tk()
#Give a title to window
root.title("CF")
l1 = Label(root, text = "Entry ").grid(row = 0, column = 0)
e1 = Entry(root, bd = 5).grid(row = 0, column = 1)
#calling event loop
root.mainloop()

Output

entry in tkinter

 

Frame

This widget is a container to organize the other widget in the application

from tkinter import *

#Creating window
root = Tk()
#Give a title to window
root.title("CF")

f1 = Frame(root,height = 60, width = 60, bg = "Red").grid(row = 0, column = 0)
f2 = Frame(root,height = 60, width = 60, bg = "Green").grid(row = 0, column = 1)
l1 = Label(f1, text = "Frame 1").grid(row = 0, column = 0)
l2 = Label(f2, text = "Frame 2").grid(row = 0, column = 1)
#calling event loop
root.mainloop()

Output

frame in tkinter

 

In this, there are two frames, one with red background and the other with green background. Both the frames contain a label inside them.

 

Check Box

This widget is used for displaying the options in the form of checkboxes.

from tkinter import *

#Creating window
root = Tk()
#Give a title to window
root.title("CF")

v1 = IntVar()
v2 = IntVar()

c1 = Checkbutton(root, text = "python", variable = v1, onvalue = 1, offvalue = 0)
c2 = Checkbutton(root, text = "JavaScript", variable = v2, onvalue = 1, offvalue = 0)
c1.pack()
c2.pack()
#calling event loop
root.mainloop()

Output

checkbox tkinter

 

Radio Button

This widget is used for selecting a single option from multiple options.

from tkinter import *
#Creating window
root = Tk()
#Give a title to window
root.title("CF")

v1 = IntVar()

r1 = Radiobutton(root, text = "python", variable = v1, value = 1)
r2 = Radiobutton(root, text = "JavaScript", variable = v1, value = 2)
r3 = Radiobutton(root, text = "Java", variable = v1, value = 3)
r4 = Radiobutton(root, text = "php", variable = v1, value = 4)
r1.pack()
r2.pack()
r3.pack()
r4.pack()
#calling event loop
root.mainloop()

Output

radiobutton

 

Message box

A message box is a pop-up box that is used to show a certain message in the application. Those messages are error messages, warning messages, ask to choose the message,s, and so on.

Messagebox provides many functions such as showinfo(), showerror(), askokcancel(), askquestion(), askyesno() and so on. In this tutorial, we’ll be looking at some of the functions mentioned above.

from tkinter import *
from tkinter import messagebox

#Creating window
root = Tk()
#Give a title to window
root.title("CF")
def fun():
    messagebox.showerror("Error 404")

b1 = Button(root, text = "send", command = fun)
b1.pack()
#calling event loop
root.mainloop()

Output

message box tkinter

 

Let’s take a look at one more example

from tkinter import *
from tkinter import messagebox
#Creating window
root = Tk()
#Give a title to window
root.title("CF")
def fun():
    messagebox.askquestion("Are You Sure..?")

b1 = Button(root, text = "send", command = fun)
b1.pack()
#calling event loop
root.mainloop()

Output

ask question tkinter

 

This is how a message box helps to display the important message.

Now, implementing what we’ve learned till now, we’re going to build a rock paper scissor game using Tkinter. Here is the source code and some of the snippets of the output

from tkinter import *
from tkinter import messagebox
import random
root = Tk()
root.geometry('500x500')
root.title("Rock Paper Scissor with GUI")
option = ["rock", "paper", "scissor"]

def fun1():
    val = e1.get()
    l2 = Label(f1, text = "your choice is : " + val, font = ("Helvetica", "12"))
    l2.grid(row=2, column = 0)
    
def fun2():
    comp = random.choice(option)
    l4 = Label(f2, text = "Computer's Choice : " + comp, font = ("Helvetica", "12"))
    l4.grid(row = 4, column = 0)
    
    human = e1.get()
    if human == "rock" and comp == "paper":
        messagebox.askokcancel("Result", "You lose....!!")
    elif human == "rock" and comp == "scissor":
        messagebox.askokcancel("Result", "You won.....!!")
    elif human == "rock" and comp == "rock":
        messagebox.askokcancel("Result", "same pick--Draw")
               
    elif human == "paper" and comp == "rock":
        messagebox.askokcancel("Result", "You won.....!!")
    elif human == "paper" and comp == "scissor":
        messagebox.askokcancel("Result", "You lose....!!")
    elif human == "paper" and comp == "paper":
        messagebox.askokcancel("Result", "same pick--Draw")
               
    elif human == "scissor" and comp == "rock":
        messagebox.askokcancel("Result", "You lose....!!")
    elif human == "scissor" and comp == "paper":
        messagebox.askokcancel("Result", "You won.....!!")
    elif human == "scissor" and comp == "scissor":
        messagebox.askokcancel("Result", "same pick--Draw")
    
        

#for user
f1 = Frame(root, width=400, height=600, highlightbackground='red', highlightthickness=3)
f1.grid(row=0, column=0, padx=20, pady=20, ipadx=20, ipady=20)

#for CPU
f2 = Frame(root, width=400, height=200, highlightbackground='blue', highlightthickness=3, bg = "white")
f2.grid(row=1, column=0, padx=20, pady=20, ipadx=20, ipady=20)


#frame 1

l1 = Label(f1, text = "Enter your choice", font = ("Helvetica", "16"))
l1.grid(row = 0, column = 0)
e1 = Entry(f1, borderwidth = 5, fg = "red", bg = "white", font = ("Helvetica", "12"))
e1.grid(row = 1, column = 0)
b1 = Button(f1, text = "send", command=fun1)
b1.grid(row = 1, column = 1)

#frame2

b2 = Button(f2, text = "Click me", command = fun2)
l3 = Label(f2, text = "Click for Compter's Choice", font = ("Helvetica", "16"))
l3.grid(row = 0, column = 0)
b2.grid(row=2, column = 0)

root.mainloop()

Output

output tkinter

 

 

Conclusion

Tkinter module in python provides an easy and fast method for developing GUI applications. For creating GUI applications, first, we will import the Tkinter module, create a window, add widgets and call an event loop to see the result on our screen.

Among geometry management methods, pack() provides a block type representation of the widget while grid() provides a table-like arrangement. Turtle, Kivy, and PyQt are some other frameworks for the development of GUI.

You can learn more about the Tkinter module here

Happy learning 🙂

Leave a Comment