Tkinter is the standard interface for Python’s Tk GUI (Graphical user interface) toolkit and de facto standard GUI. A GUI lets you interact with your computer using visual items (such as Windows, ICONS, and menus) that most operating systems use. This powerful tool can be used to build a variety of projects and make visualizing code easier.

In this article, you’ll learn the basics of Tkinter and the different types of widgets you can use in Python applications. Later in this article, we’ll use the Tkinter widget to develop a cool number guessing game.

Today, we will introduce:

  • The basis of Tkinter
  • Tkinter widgets with examples
  • Build number guessing games from scratch

The basis of Tkinter

Before we can build our game, we need to know the basics of Tkinter. The Tkinter package is the standard Python interface to the Tk GUI toolkit. We typically use Tkinter packages to insert different GUI widgets into the application to make it more user-friendly. If you use Python on Linux, Windows, or Mac, you have Python Tkinter installed on your device.

How do we develop GUI applications?

The basic process for creating a GUI application is as follows:

Import the Tkinter ModuleCreate Main WindowAdd WidgetsEnter Main Loop

Developing GUI applications using Python involves the following steps:

  • Import the tkinter module.
  • Create the main window for our GUI application.
  • Now, add any number of widgets to our application.
  • Enter the main event loop to perform our main function.

Now let’s see how to create a simple Tkinter window:

First, we will import the Tkinter module. It contains all the functionality, classes, and other things you need to build your application. Now, when we import the module, we need to initialize tkinter. To do this, we create the Tk() root widget. This will now create our main GUI window, where we will add the widget. At this point, our main window only has the title bar.

We should only create one window for our application and must do so before adding any other widgets. After that, we use root.mainloop(). The main window we just created, Mainloop, will not display unless entered. When we press the close button, our program will exit the main loop. Our application will run until the close button is pressed.

Code for creating a simple Tkinter window:

#import required libraries
from tkinter import *

# initialize tkinter :
root = Tk()

# enter the main Loop :
root.mainloop()
Copy the code

Tkinter widgets with examples

  • ** button: ** display button.
  • ** Canvas: ** Draw shapes.
  • ** Check boxes: ** displays multiple options as check boxes.
  • ** Input: ** accepts single-line input from the user.
  • ** framework: ** organizes other widgets.
  • ** Tags: ** Adds titles to other widgets.
  • ** List box: ** provides the user with a list of options.
  • Menu ** button: ** displays the menu in our application.
  • ** Menu: ** provides various commands to the user.
  • ** messages: ** displays multi-line text fields.

  • ** Radio buttons: ** Displays the number of options as radio buttons.
  • ** Scale: ** slider is provided.
  • ** Scroll bar: ** Adds scroll function.
  • ** Text: ** displays text in multiple lines.
  • ** Top layer: ** provides a separate window container.
  • **Spinbox: ** Select from fixed input values.
  • **PanedWindow: ** Arranges widgets horizontally or vertically.
  • **LabelFrame: ** Provides space with a complex structure.
  • **tkMessageBox: ** Displays a message box in the application.

Now, we’ll briefly cover some of the widgets needed in the In Out application. Keep in mind that we will demonstrate the widget in its simplest form here. There are many more functions available in each widget. We’ll see some of these as we develop games.

Some examples of Tkinter widgets

Buttons: The button widget is used to display buttons in our application. Usually, when we press a button, there will be a command associated with it.

# Import required libraries :
from tkinter import *

# Initialize tkinter :
root = Tk()

# Adding widgets :

# Add button :
btn = Button(root,text="PRESS ME",command=lambda:press())
# Place button in window : 
btn.grid(row=0,column=0)

# Define the function :
def press()
  lbl = Label(root,text="You Pressed The Button")
  lbl.grid(row=0,column=1)

# Enter the main Loop : 
root.mainloop()
Copy the code

** Tags: The ** tag widget is used to provide single-line headers for other widgets in our application.

# Import required libraries :
from tkinter import *

# Initialize tkinter :
root = Tk()

# Adding widgets :

# Add label :
lbl = Label(root,text="This is label")

# Place the button on window :
lbl.grid(row=0,column=1)

# Enter the main Loop :
root.mainloop()
Copy the code

Canvas: The canvas widget is used to draw various shapes.

# Import required libraries : from tkinter import * # Initialize tkinter : root = Tk() # Adding widgets : # Add canvas : # Create canvas object : c = Canvas(root,bg="3389db",height=250,width-300) # Draw a straight line : Line = c.create_line(0,0,50,50) # To fit the line in the window c.pack() # Enter the mainloop root.mainloop()Copy the code

**CheckButton: ** We use CheckButton to display multiple options available to the user. Here, the user can select multiple options.

# Import required libraries :
from tkinter import *

# Initialize tkinter :
root = Tk()

# Adding widgets : 
# Add checkbutton : 

# IntVar() hold integers
# Default value is 0
# If checkbox is marked, this will change to 1
checkvar1 = IntVar()
checkvar2 = IntVar()

# Create checkbutton 
c1 = Checkbutton(root,text="BMW", variable=checkvar1)
c2 = Checkbutton(root,text="Audi",variable=checkbar2)

# To fit in the main window
c1.grid(row=0,column=0)
c2.grid(row=1,column=0)

# Enter the main Loop
root.mainloop()
Copy the code

Entry:The Entry widget is used to accept a single line of input from the user.

# Import required libraries 
from tkinter import *

# Initialize tkinter
root = Tk()

# Adding widgets 
# Label 
lbl = Label(root,text="Enter your name:")
lbl.grid(row=0,column=0)

# Entry 
e = Entry(root)
e.grid(row=0,column=1)

# Enter the main Loop
root.mainloop()
Copy the code

** Framework: ** is used as a container widget to organize other widgets in the same application

# Import required libraries 
from tkinter import *

# Initialize tkinter
root = Tk()

# Adding widgets 

frame = Frame(root)
frame.pack()

# Add button on Left
A = Button(frame,text="A")
A.pack(side = LEFT)

# Add button on Right 
B = Button(frame,text="B")
B.pack(side = RIGHT)

# Enter the main Loop
root.mainloop()
Copy the code

** List box: ** is used to provide the user with a list of options.

# Import required libraries 
from tkinter import *

# Initialize tkinter
root = Tk()

# Adding widgets 

# Create Listbox : 
Lb = Listbox(root)

# Add items in list
Lb.insert(1,"A")
Lb.insert(2,"B")
Lb.insert(3,"C")
Lb.insert(4,"D")

# Place listbox on window 
Lb.grid(row=0,column=0)

# Enter the main Loop
root.mainloop()
Copy the code

Build number guessing games from scratch

Step by step drill

When the user runs the program, our code will generate a random number between 0 and 9. The user will not know the randomly generated number. Now, the user must guess the value of a randomly generated number. The user enters a value in the input box. After that, the user will press the check button. This button will trigger the function. This function checks whether the number entered by the user matches the randomly generated number. If the number guessed is correct, the program will display the correct label and the actual number (in this case, the number will be the same as the number guessed).

Now, if the guess number is less than the randomly generated number, our program will display the TOO LOW label, and this will also clear the input field so the user can enter a new number.

If the guess number is higher than the actual number, our program displays the TOO HIGH label and clears the input box. That way, the user can continue to guess the correct number.

If the tag says TOO HIGH, the user should enter a lower number than they guessed. If the tag says TOO LOW, the user should enter a larger number than they first guessed.

Our program will also count how many attempts it takes the user to guess the correct number. When the user finally makes a correct guess, it shows the total number of attempts.

If the user wants to play a new game, the main close button must be pressed. If a user presses the “** Close” ** button in our application, they will quit the game completely.

Just a few simple steps:

  • Run the application.
  • Enter your guess.
  • Press the check button.
  • If the label is displayed incorrectly, guess a new number.
  • If the label is displayed correctly, the number of attempts is displayed.
  • Press the main close button to restart the game with a new number.
  • Press the close button from our app to exit the game completely.
! [Python Tkinter Tutorial Series 02: Figure Guessing Game Illustrations (12)](Data :image/ GIF; Base64, R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw = = “Python Tkinter tutorial series 02: We will show you step by step how to build the above game using Python Tkinter.

Picture materials here IT station, here to download digital guessing game materials

Step 1: Import the required libraries

# import required libraies :

from tkinter import * # to add widgets
import random # to generate a random number
import tkinter.font as font # to change properties of font
import simpleaudio as sa # to play sound files
Copy the code

Step 2: Create the main Tkinter window

want_to_play = True while want_to_play==True: root = Tk() root.title("Guess The Number!" ) root.geometry('+100+0') root.configure(bg="#000000") root.resizable(width=False,height=False) root.iconphoto(True,PhotoImage(file="surprise.png"))Copy the code

  • First, we create a variable namedwant_to_playAnd sets its value toTrue. When the variable is set, our program will generate a new windowTrue. When the user presses the main close button, it exits the loop, but in this case, we set the variable toTrue, so it will create another window with the newly generated number.
  • root = Tk( ): used to initialize our tkinter module.
  • root.title( ): We use it to set the title of the application.
  • root.geometry( ): We use it to specify where our application window will open.
  • root.configure( ): We use it to specify the background color of the application.
  • root.resizable( )Here we use it to prevent the user from resizing the main window.
  • root.iconphoto( ): We use it to set the icon in the title bar of the application window. We set the first parameter toTrue.

Step 3: Import the sound file

# to play sound files 
start = sa.WaveObject.from_wave_file("Start.wav")
one = sa.WaveObject.from_wave_file("Win.wav")
two = sa.WaveObjet.from_wave_file("Lose.wav")
three = sa.WaveObject.from_wave_file("Draw.wav")

start.play()
Copy the code

Now, we’ll use some sound files that will play at various events. When our program starts, it will play the start file. When the user guesses correctly, when the user guesses incorrectly, and when the user closes the application, we play the remaining three files, respectively. One thing to note is that it only accepts.wav files. First, we need to load the sound file into the object. Then we can.play() use the method to play it as needed.

Step 4: Load the image for our application

We will use various images in our application. To use these images first, we need to load them. In this case, we’ll load the image using the PhotoImage class.

# Loading images
Check = PhotoImage(file="Check_5.png")
High = PhotoImage(file="High_5.png")
Low = PhotoImage(file="Low_5.png")
Correct = PhotoImage(file="Correct_5.png")
Surprise = PhotoImage(file="Surprise.png")
your_choice = PhotoImage(file="YOUR_GUESS.png")
fingers = PhotoImage(file="fingers.png")
close = PhotoImage(file="Close_5.png")
Copy the code

Step 5: Generate random numbers

Here, we will generate random numbers between 1 and 9. We will use the random module to generate random integers between 1 and 9.

# generating random number number = random. Randint (1,9)Copy the code

Step 6: Modify the font

Here, we will use the font module to change the fonts in the application.

# using font module to modify fonts
myFont = font.Font(family='Helvetica',weight='bold')
Copy the code

Step 7: Add widgets

Here we add the first two widgets of the application. Notice that the input field is on line 2 because we added a space on line 1. In this case, we will use the image file in the tag. We use.grid() to specify the location of a particular widget.

# Creating first label
label = Label(root,image=your_choice)
label.grid(row=0,column=1)

# Creating the entry box 
e1 = Entry(root,bd=5,width=13,bg="9ca1db",justify=CENTER,font=myFont)
e1.grid(row=2,column=1)
Copy the code

Step 8: Add additional widgets

Here, we’ll add some other widgets, such as buttons and labels. There will be two buttons, one to check the value and one to permanently close the window. The second TAB shows whether the user guessed the value to be correct, high, or low. It will display the label accordingly. If the user guesses correctly, the third TAB will display the correct number.

The fourth TAB shows the total number of attempts the user made to guess the correct value. Notice here that these two buttons will trigger the command. We will examine this in the next few points.

# Creating check button :
b1 = Button(root,image=Check,command=lambda:show())
b1.grid(row=4,column=3)

# Creating close button :
b2 = Button(root,image=close,command=lambda:reset())

#Creaating second label :
label2 = Label(root,image=fingers)
label2.grid(row=6,column=1)

#Creating third label :
label3 = Label(root,image=Surprise)
label3.grid(row=10,column=1)

#Creating fourth label :
label4= Label(root,text="ATTEMPTS : ",bd=5,width=13,bg="#34e0f2",justify=CENTER,font=myFont)
label4.grid(row=12,column=1)
Copy the code

Step 9: Display the correct image and set the counter to the trial value

When the user guesses correctly, we will display the correct digital image here. Our digital storage is as follows:

  • 1.png
  • 2.png
  • 3.png
  • 100.png

Therefore, our program will take the actual number, add a.png string to it and open the file. We will also set the counter to calculate the trial value. It stores the number of attempts required to guess the correct number.

# to display the correct image
num = PhotoImage(file = str(number)+str(".png"))

# Set the count to 0
count = 0
Copy the code

Step 10: The function that will trigger when we press the check button

In this case, each time the user presses the check button, the count of attempts increases by one. We then store the value entered by the user in a variable named answer. We will then check if the user has not entered any values and press the check button, which will go to the Reset () function and the application will close.

Now we must convert the value entered by the user to an integer so that we can compare it to the actual number.

def show(): #Increase the count value as the user presses check button. global count count = count+1 #Get the value entered by user.  answer = e1.get() #If the entry value is null the goto reset() function. if answer=="": reset() #Convert it to int for comparision. answer = int(e1.get()) if answer > number: #Play sound file. two.play() #Change the label to Too High. label2.configure(image=High) #Calls all pending idle tasks. root.update_idletasks() #Wait for 1 second. root.after(1000) #Clear the entry. e1.delete(0,"end") #Change the label to the original value. label2.configure(image=fingers) elif answer < number: #Play sound file. two.play() #Change the label to Too Low. label2.configure(image=Low) #Calls all pending idle tasks. root.update_idletasks() #Wait for 1 second. root.after(1000) #Clear the entry. e1.delete(0,"end") #Change the label to the original value. label2.configure(image=fingers) else: #Play sound file. one.play() #Show the CORRECT image. label2.configure(image=Correct) #Show the correct number. label3.configure(image=num) #Show the number of attempts. label4.configure(text="ATTEMPTS : "+str(count))Copy the code

Step 11: The “Close” button will triggerreset()function

This function sets the want_to_play variable to False so that our application shuts down and does not start again. It will then close the main window of our application.

# define reset() function 
def reset():
  # Play sound file 
  three.play()
  # Change the variable to false
  global want_to_play
  want_to_play = false
  # Close the tkinter window
  root.destroy()
Copy the code

Step 12: Main loop

We have to go into the main loop to run the program. If our program doesn’t have this line, it won’t work. Our program will remain in the main loop until we press the close button.

# Enter the mainLoop
root.mainloop()
Copy the code

The complete code

#Import required libraries : from tkinter import * import random import tkinter.font as font import simpleaudio as sa want_to_play = True while want_to_play==True: root = Tk() root.title("Guess The Number!" ) root.geometry('+100+0') root.configure(bg="#000000") root.resizable(width=False,height=False) root.iconphoto(True,PhotoImage(file="surprise.png")) #To play sound files: start = sa.WaveObject.from_wave_file("Start.wav") one = sa.WaveObject.from_wave_file("Win.wav") two = sa.WaveObject.from_wave_file("Lose.wav") three = sa.WaveObject.from_wave_file("Draw.wav") start.play() #Loading images :  Check = PhotoImage(file="Check_5.png") High = PhotoImage(file="High_5.png") Low = PhotoImage(file="Low_5.png") Correct = PhotoImage(file="Correct_5.png") Surprise= PhotoImage(file ="Surprise.png") your_choice = PhotoImage(file="YOUR_GUESS.png") fingers = PhotoImage(file = "Fingers.png") close = PhotoImage(file="Close_5.png") #To have space between rows. root.grid_rowconfigure(1, minsize=30) root.grid_rowconfigure(3, minsize=30) root.grid_rowconfigure(5, minsize=30) root.grid_rowconfigure(9, minsize=30) root.grid_rowconfigure(11, Minsize =30) #Generating random number: number = random. Randint (1,9) #Using font module to modify the fonts: myFont = font.Font(family='Helvetica',weight='bold') #Creating the first label : label = Label(root,image=your_choice) label.grid(row=0,column=1) #Creating the entry box : e1 = Entry(root,bd=5,width=13,bg="#9ca1db",justify=CENTER,font=myFont) e1.grid(row=2,column=1) #Creating check button : b1 = Button(root,image=Check,command=lambda:show()) b1.grid(row=4,column=3) #Creating close button : b2 = Button(root,image=close,command=lambda:reset()) b2.grid(row=4,column=0) #Creaating second label : label2 = Label(root,image=fingers) label2.grid(row=6,column=1) #Creating third label : label3 = Label(root,image=Surprise) label3.grid(row=10,column=1) #Creating fourth label : label4= Label(root,text="ATTEMPTS : ",bd=5,width=13,bg="#34e0f2",justify=CENTER,font=myFont) label4.grid(row=12,column=1) #To display the correct image : num = PhotoImage(file=str(number)+str(".png")) #Set the count to 0. #It stores the attempt value. count = 0 def show(): #Increase the count value as the user presses check button. global count count = count+1 #Get the value entered by user.  answer = e1.get() #If the entry value is null the goto reset() function. if answer=="": reset() #Convert it to int for comparision. answer = int(e1.get()) if answer > number: #Play sound file. two.play() #Change the label to Too High. label2.configure(image=High) #Calls all pending idle tasks. root.update_idletasks() #Wait for 1 second. root.after(1000) #Clear the entry. e1.delete(0,"end") #Change the label to the original value. label2.configure(image=fingers) elif answer < number: #Play sound file. two.play() #Change the label to Too Low. label2.configure(image=Low) #Calls all pending idle tasks. root.update_idletasks() #Wait for 1 second. root.after(1000) #Clear the entry. e1.delete(0,"end") #Change the label to the original value. label2.configure(image=fingers) else: #Play sound file. one.play() #Show the CORRECT image. label2.configure(image=Correct) #Show the correct number. label3.configure(image=num) #Show the number of attempts. label4.configure(text="ATTEMPTS : "+str(count)) #Define reset() function : def reset(): #Play the sound file. three.play() #Change the variable to false. global want_to_play want_to_play = False #Close the tkinter window. root.destroy() #Enter the mainloop : root.mainloop()Copy the code