Tkinter Tutorial For Beginners
Tkinter Tutorial For Beginners
Anirudh RaoResearch Analyst at Edureka who loves working on Neural Networks and Deep Learning!
Bookmark
o What is a Graphical User Interface (GUI)?
o Python Libraries to create GUIs
o What is Tkinter?
o Fundamentals of Tkinter
o Tkinter Widgets
o Geometry Management
o Organization of Layouts and Widgets
o Binding Functions
o Images and Icons
o Use Case – Calculator Application using Tkinter
Apps like Sudoku, Chess and Solitaire are games which you can play.
They are some different types of GUI apps which we daily use on the laptops or
desktops. We are going to learn how to create those type of apps.
As this is an Introduction to GUI, make sure you stay tuned till the end as we will create
a really simple and nice GUI app.
Well, it is a personal preference that I prefer GUI over command line. Not that there is
something wrong with the command line but I prefer more intuitive and interactive
applications with a lot of visuals.
What do you prefer? Head to the comment section and let me know.
Next up on this Tkinter tutorial blog, let us check out the Python libraries that are
present for designing our own GUI.
Kivy
Python QT
wxPython
Tkinter
Among all of these, Tkinter is the first choice for a LOT of learners and developers just
because of how simple and easy it is.
Note: It is at this point that I’d like to mention that you will require a little bit of knowledge
about Python to start working with Tkinter. There is nothing to worry if you don’t have
any prior programming experience with Python. I have created an in-depth python
tutorial specifically for beginners which I have linked at the end of this blog, I am getting
some really good feedback on it so I’d recommend you guys to check it out when you’re
done reading this Tkinter tutorial blog.
Next up on this Tkinter tutorial blog, let us check out what Tkinter actually is.
What Is Tkinter?
Tkinter is actually an inbuilt Python module used to create simple GUI apps. It is the
most commonly used module for GUI apps in the Python.
I am going to use Python 3.6 version for this tutorial. So, kindly update Python if you’re
using below versions.
Another advice for you guys is to not blindly copy the code. Try to write by modifying it
as you like and then observing and understanding the resulting changes.
Next up on this Tkinter tutorial blog, let us check out the fundamentals of Tkinter so that
we can go about creating our own GUIs.
Fundamentals Of Tkinter
Consider the following diagram, it shows how an application actually executes in
Tkinter:
To start out with, we first import the Tkinter model. Followed by that, we create the main
window. It is in this window that we are performing operations and displaying visuals
and everything basically. Later, we add the widgets and lastly we enter the main event
loop.
If you noticed, there are 2 keywords here that you might not know at this point. These
are the 2 keywords:
Widgets
Main Event Loop
An event loop is basically telling the code to keep displaying the window until we
manually close it. It runs in an infinite loop in the back-end.
1 import tkinter
2
3 window = tkinter.Tk()
4
5 # to rename the title of the window window.title("GUI")
6
7 # pack is used to show the object in the window
8
label = tkinter.Label(window, text = "Hello World!").pack()
9
10
window.mainloop()
11
As you can see, we are importing the Tkinter package and defining a window. Followed
by that, we are giving a window title which is shown on the title tab whenever you open
an application.
For example, Microsoft Word is shown on the title tab when you open a word
application, correct? Similarly here we call it GUI. We can call it anything we want based
on the requirement.
Lastly, we have a label. A label is nothing is but what output needs to be shown on the
window. In this case as you can already see, it is hello world.
Next up on this Tkinter tutorial blog, let us look at the massive range of widgets offered
by Tkinter.
Tkinter Widgets
The first question we need to ask is, what are widgets?
Widgets are something like elements in the HTML. You will find different types
of widgets to the different types of elements in the Tkinter.
Let’s see the brief introduction to all of these widgets in the Tkinter.
Check out this diagram for the list of the majorly used Tkinter widgets:
These widgets are the reason that Tkinter is so popular. It makes it really easy to
understand and use practically.
Let us walk through all of these widgets individually for better understanding.
Do note that I will not overwhelm you with the complete syntax for every single widget.
The code snippets are more than sufficient to make your learning easier and I’ve done
this just so you can avoid any sort of confusion or ambiguity while learning.
Label Widget:
As mentioned earlier, labels are used to create texts and images and all of that but it is
important to note that it has to be a single line definition only.
There is something called as the geometry function. We will be walking through this in
the coming sections as well.
At this point of time all you need to know is that it is basically used to change the
window size and set as per our requirement.
The next widget we will check on this Tkinter tutorial blog is the button widget.
Explore Curriculum
Button Widget:
The button widget is very similar to the label widget. We create a variable and use the
widget syntax to define what the button has to say.
We can also change the foreground for a button or any other widget as well. We will be
using the parameter FG as shown in the code. Similarly, the background colour can be
changed as well using the BG property.
So at this point, we have a clickable button. Well, what happens when we actually go
ahead and click it?
1 def clicked():
2
3 l1.configure (text="Button was clicked !!")
4
5 bt = Button (window, text=“Enter”, command=clicked)
So we call this the click event. We need to write the functionality as to what should
happen when we click the button or in other terms when the click event is fired.
For that purpose we have a function called clicked, we are displaying a text message
saying button was clicked.
We will need to add a parameter called command in the button definition as shown.
The next widget we will check on this Tkinter tutorial blog is the entry widget.
Entry Widget:
What is an entry widget used for?
1 txt = Entry(window,width=10)
2
3 txt.grid(column=1, row=0)
4
5 def clicked():
6
7 res = "Welcome to " + txt.get()
8
9 l1.configure(text= res)
10
bt = Button (window, text=“Enter”, command=clicked)
11
Here, we are creating a textbox using the Tkinter entry class. The grid tells the code
where we want the widget on the window.
Well, we have a message that says ‘Welcome to’ and later whatever is input into the
text area will be concatenated along with this and printed.
Check out the output. We’ve typed Python Training and so it displays welcome to
python training.
Output:
All these widgets are really simple and more than that they always come in handy as
well.
The next widget we will check on this Tkinter tutorial blog is the combobox widget.
Combobox Widget
Can you take a quick guess on what a combobox widget is?
It is defined using double quotes and we later will set the selected input. Followed by
that, we have the grid function to place the widget on the window.
So we have the drop-down menu and it displays all that we’ve defined in the code. Here
is the output for the code:
The next widget we will check on this Tkinter tutorial blog is the Checkbutton widget.
Checkbutton Widget:
The checkbutton is widely used in almost all the sites.
Code snippet:
1 chk_state = BooleanVar()
2 chk_state.set (True)
3 chk = Checkbutton(window, text=‘Select', var=chk_state)
chk.grid(column=0, row=0)
4
We start by creating a variable of the type booleanvar.
But this is not a standard python variable, correct? Well nothing to worry, this is a
Tkinter variable.
By default, we keep the set state to be true which means that the button is checked
already. And next, we are passing chk_state to the checkbutton class to set the check
state for us.
Output:
Check out the above output. So we have a really simple checkbutton widget with a
certain text.
The next widget we will check on this Tkinter tutorial blog is the radio button widget.
Similarly, the grid function used to place the widget on the window.
Output:
From the above output, do note that unlike a checkbutton where you can try selecting
multiple, here in case of radio button you can only select one at a time.
The next widget we will check on this Tkinter tutorial blog is the scrolled text widget.
Code:
You can set the scrolled text content by using the insert method. The syntax is pretty
simple. We need to use txt.insert with the message as a parameter.
Output:
The next widget we will check on this Tkinter tutorial blog is the message box widget.
Code:
See, this is where things get interesting. Look at the snippet below:
1 def clicked():
2 messagebox.showinfo('Message title', 'Message content')
3
4 btn = Button(window,text=‘ENTER', command=clicked)
Here we have made use of two of the widgets we learnt. We are using a button click to
show a message box for us.
Last but not least, we will check out the Spinbox widget on this Tkinter tutorial.
SpinBox Widget:
Spinbox is a popular widget as well. There are two tabs, the up and down scroll tabs
present. This is how it differs from the scroll down widget. Here the static number will
change over a certain range of values.
Code:
1 spin = Spinbox(window, from_=0, to=100, width=5)
We have 3 parameters – from, to and width. From – tells the start and the default value
of the range and to – gives us the upper threshold of the range.
Width is basically to set the size of the widget to 5 character spaces. But since are
doing 0 to 100, 3 is sufficient for us but I have gone ahead and put 5 just so it looks well
placed.
You can put whatever you want here and it’s valid but make sure it is more than what
the range can offer.
Output:
Next up on this Tkinter tutorial blog, we need to check out geometry management.
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 and
so on.
Tkinter has the following three Geometry Manager classes.
pack():- It organizes the widgets in the block, which mean it occupies the entire
available width. It’s a standard method to show the widgets in the window.
grid():- It organizes the widgets in table-like structure.
place():- It places the widgets at a specific position you want.
We already looked at the grid in almost all of the previous codes. If you have any
doubts, head to the comment section and leave a comment, let’s interact there.
Next up on this Tkinter tutorial blog, we need to check out how we can organize layouts
and widgets.
Steps:-
Frame creates the divisions in the window. You can align the frames as you like
with side parameter of pack() method.
1
2 import tkinter
3 window = tkinter.Tk()
window.title("GUI")
4 # creating 2 frames TOP and BOT
5 top_frame = tkinter.Frame(window).
6 bottom_frame = tkinter.Frame(window).pack(s
7 # now, create some widgets in the top_frame
btn1 = tkinter.Button(top_frame, text = "Button1", fg = "red").pack()# 'fg
8 btn2 = tkinter.Button(top_frame, text = "Button2", fg = "green").pack()# '
9 btn3 = tkinter.Button(bottom_frame, text = "Button2", fg = "purple").pack(sid
10 btn4 = tkinter.Button(bottom_frame, text = "Button2", fg =
11 window.mainloop()
12
Above code produces the following window, if you didn’t change the above code.
See the below example to get an idea of how it works.
1
2 import tkinter
3 window = tkinter.Tk()
window.title("GUI")
4 # creating 2 text labels and input
5 tkinter.Label(window, text = "Username").grid(row = 0
6 # 'Entry' is used to display the inp
7 tkinter.Entry(window).grid(row = 0, column = 1) #
8 tkinter.Label(window, text = "Password").grid(row = 1
tkinter.Entry(window).grid(row = 1, column = 1) #
9 # 'Checkbutton' is used to create the c
10 tkinter.Checkbutton(window, text = "Keep Me Logged In").grid(columnspan = 2) #
11 # you can also use 'rowspan' in the sim
12 window.mainloop()
13
You will get the following output:
Next up on this Tkinter tutorial blog, we need to check out a concept called binding
functions.
Binding Functions
Calling functions whenever an event occurs refers to a binding function.
In the below example, when you click the button, it calls a function called say_hi.
1 import tkinter
window = tkinter.Tk()
2
window.title("GUI")
3 # creating a function called say_hi()
4 def say_hi():
5
6
7 tkinter.Label(window, text = "Hi").pa
tkinter.Button(window, text = "Click Me!", command = say_hi).pack() # 'command
8 # in this above case we're calling the function
9 window.mainloop()
10
The above program will produce the following results:
The following program also produces the same output as the above one:
1
2 import tkinter
window = tkinter.Tk()
3 window.title("GUI")
4 # creating a function with an arguments 'event'
5 def say_hi(event): # you can rename 'event' to anything you want
6
7 tkinter.Label(window, text = "Hi").pack()
btn = tkinter.Button(window, text = "Click Me!")
8 btn.bind("Button-1", say_hi) # 'bind' takes 2 parameters 1st is 'event' 2nd is
9 btn.pack()
10 window.mainloop()
11
‘<Button-1>‘ parameter of bind method is the left clicking event, i.e., when you
click the left button the bind method call the function say_hi
o <Button-1> for left click
o <Button-2> for middle click
o <Button-3> for right click
Here, we are binding the left click event to a button. You can bind it to any
other widget you want.
You will have different parameters for different events
Now, you will learn how to call a particular function based on the event that occurs.
Run the following program and click the left, middle, right buttons to calls a
specific function.
1
2 import tkinter
3 window = tkinter.Tk()
4 window.title("GUI")
#creating 3 different functions for 3 events
5 def left_click(event):
6
7 tkinter.Label(window, text = "Left Click!").pack()
8 def middle_click(event):
9
10 tkinter.Label(window, text = "Middle Click!").pack()
def right_click(event):
11
12
tkinter.Label(window, text = "Right Click!").pack()
13 window.bind("Button-1", left_click)
14 window.bind("Button-2", middle_click)
15 window.bind("Button-3", right_click)
16 window.mainloop()
17
If you run the above program, you will see a blank window. Now, click the left, middle
and right button to call respective functions.
1
import tkinter
2 window = tkinter.Tk()
3 window.title("GUI")
4 # taking image from the directory and storing the source in a vari
5 icon = tkinter.PhotoImage(file = "images/edureka.png")
6 # displaying the picture using a 'Label' by passing the 'picture' variriable to
label = tkinter.Label(window, image = icon)
7 label.pack()
8 window.mainloop()
9
You can see the icon in the GUI:
Understand the Tkinter code.
Create frames, labels, buttons, binding functions, events and all.
To develop simple GUI apps.
So next up on this Tkinter Tutorial blog, we’re going to create a simple Calculator
GUI with all the stuff that we’ve learned till now.
Conclusion
The concepts discussed in this tutorial should help you make your own GUI apps and
add functionality to the same.
This will be very handy when you are trying to create a customized application with a
GUI that suits your personal needs. Now, you should also be able to use these widgets
and images to develop applications easily with the help of Python.
After reading this blog on Tkinter tutorial using Python, I am pretty sure you want to
know more about Python. To know more about Python you can refer the following
blogs:
I hope you have enjoyed this post on Tkinter Tutorial. If you have any questions
regarding this tutorial, please let me know in the comments.