Tkinter Starter v8 Incomplete
Tkinter Starter v8 Incomplete
8
In this tutorial, we will learn how to develop graphical user interfaces by writing some
Python GUI examples using the Tkinter package. This tutorial was edited from an online
resource. As of 2023 it appears to no longer be available but credit is given:
https://dzone.com/articles/python-gui-examples-tkinter-tutorial-like-geeks
In this tutorial, we will learn how to develop graphical user interfaces by writing some Python GUI examples
using the Tkinter package.
Tkinter package is shipped with Python as a standard package, so we don't need to install anything to use it.
Tkinter is a very powerful package. If you already have installed Python, you may use IDLE which is the
integrated IDE that is shipped with Python, this IDE is written using Tkinter. Sounds Cool!!
We will use Python 3.x, so if you are using Python 2.x, please switch to Python 3.x.
It is assumed that you have a little background in the Python basics to help you understand what we are doing.
This tutorial will attempt to cover the main aspects of Python GUI development, but not all of them.
There is no tutorial or a book that can cover everything.
We will start by creating a window to which we will learn how to add widgets such as buttons, combo boxes, etc.
Then we will play with their properties, so let's get started.
window = Tk()
window.title("Welcome")
window.mainloop()
1
The main window will be the first widget we create. ALL widgets that get created should come after this one.
The last line calls the mainloop() function. This function calls the endless loop of the window,
so the window will wait for any user interaction till we close it.
If you forget to call the mainloop() function, nothing will appear to the user.
lbl = Label(window, text="Hello") Simply add the “width=##” parameter when defining
Then we will set its position on the form using the the widget.
grid function and give it the location like this:
If there are different widths specified for a column of
lbl.grid(column=0, row=0) widgets, the highest will be chosen.
So the complete code will be like this:
from tkinter import *
from tkinter import *
window = Tk()
window = Tk() window.title("Welcome")
window.title("Welcome") lbl = Label (window, text="Hello",
lbl = Label(window, text="Hello there, width=20)
this is fun!") lbl.grid(column=0, row=0)
lbl.grid()
window.mainloop()
window.mainloop()
Note that the font() parameter can be passed to any widget to change its font,
thus it applies to more than just labels.
Great, but the window is so small, what about setting the window size?
2
Setting Window Size
We can set the default window size using the geometry() function like this:
window.geometry('350x200')
The above line sets the window width to 350 pixels and the height to 200 pixels.
If the geometry is not provided, Tkinter will try to automatically size the window based on the widget contents.
Let's try adding more GUI widgets like buttons and see how to handle button click events.
Note that we place the button on the second column of the window, which is 1.
If you forget and place the button on the same column which is 0, it will show the button only,
since the button will be placed on the top of the label.
Tkinter will take into account the size of widgets in each row/column. You cannot skip rows/columns with zero
widgets as their size will be zero. To have more spacing around widgets, you could see page 2 for setting widget
width, or page 19 for adding padding around widgets. Another idea is to consider adding empty Labels or other
widgets for sizing, etc. Be creative. Play around and test ideas.
3
Change Button Foreground and Background Colours
You can change the foreground of a button or any other widget using the fg property.
Also, you can change the background colour of any widget using the bg property.
btn = Button(window, text="Click Me", bg="orange", fg="red")
Now, if you tried to click on the button, nothing happens because the click event of the button isn't written yet.
Then we will wire it with the button by specifying the function like this:
btn = Button(window, text= "Click Me", command=clicked)
Note that, we Tkinter requires that we typed clicked only, not clicked() with parentheses!
#Main Program
window = Tk()
window.title("Welcome")
window.geometry('350x200')
window.mainloop()
4
And when we click the button, the result, as expected, looks like this:
Cool!
!
NEVER NEVER NEVER NEVER NEVER create new widgets inside any “def something(): “ code!!!!!!!
You can create a textbox using Tkinter Entry() class like this:
txt = Entry(window,width=10)
Then you can add it to the window using a grid() function as usual
def clicked():
lbl.configure(text="Button was clicked !!")
window.mainloop()
5
And the result will be like this:
Now, if you click the button, it will show the same old message,
but what about showing the entered text on the Entry widget?
First, you can get entry text using the get() function.
We can write this code to our clicked() function like this:
def clicked():
res = "Welcome to " + txt.get()
lbl.configure(text = res)
If you click the button and there is text in the entry widget,
it will show "Welcome to" concatenated with the entered text.
And this is the complete code:
from tkinter import *
def clicked():
res = "Welcome to " + txt.get() Notice a new string variable for text
lbl.configure(text= res) Updates an existing widget value
window = Tk()
window.title("Welcome")
window.geometry('350x200')
6
Run the above code and check the result:
Awesome!
def addMe():
counter += int(txt.get())
lbl.configure(text = counter)
#Main Program
#global variables
counter = 0 #variable to keep track of something
window = Tk()
window.title("Welcome")
window.geometry('200x75')
txt.focus()
window.mainloop()
7
Add a Combobox Widget
To add a combobox widget, you can use the Combobox class from ttk library like this:
from tkinter.ttk import Combobox
combo = Combobox(window)
Then you can add your values to the combobox.
from tkinter.ttk import Combobox
from tkinter import *
def clicked():
lbl.configure(text = combo.get())
bttn = Button( window, text = "Press Me", command = clicked) See page 19
bttn.grid(row=2, column = 0) for “sticky=”
window.mainloop()
As you can see, we initially add the combobox items by setting ‘values’ attribute with a list of values.
To set the selected item, you pass the index of the desired item to the .current() method.
Note that lists are zero-indexed; meaning the first item is always (0), the second is (1), and so on.
To get the select item, you can use the get() function like this:
combo.get()
8
Add a Checkbutton Widget (Tkinter Checkbox)
To create a checkbutton widget, you can use the Checkbutton() class like this:
from tkinter.ttk import Checkbutton
from tkinter import *
def update_text():
likes ="" #empty text
if (chk1_state.get() == True): # could also do: if self.newHope.get():
likes+="Star Wars Episode IV: A New Hope\n"
if (chk2_state.get() == True):
likes+="Star Wars Episode V: The Empire Strikes Back\n"
if (chk3_state.get() == True):
likes+="Star Wars Episode VI: Return of the Jedi\n"
window.mainloop()
9
Also, you can use IntVar() instead of BooleanVar() and set the value to 0 or 1.
chk_state = IntVar()
chk_state.set(0) #uncheck
chk_state.set(1) #check
def clicked():
print(selected.get())
window = Tk()
window.title("Welcome")
selected = IntVar()
window.mainloop()
Every time you select a radio button, the value of the selected
variable will be changed to the value of the selected radio button.
10
Add a ScrolledText Widget (Tkinter textarea)
To add a ScrolledText widget, you can use the ScrolledText() class like this:
from tkinter import scrolledtext
txt = scrolledtext.ScrolledText(window,width=40,height=10)
We must provide the width and the height of the ScrolledText widget or else it will fill the entire window.
def click_delete():
txt.delete(0.0, END)
#Main program
#create main window
window = Tk()
window.title("Welcome")
window.geometry('350x250')
#create buttons
btn1 = Button( window, text = "Click to Add", command = click_insert)
btn2 = Button( window, text = "Click to Del", command = click_delete)
window.mainloop()
11
Create a Message Box
To show a message box using Tkinter, you can use the messagebox library like this:
from tkinter import messagebox
messagebox.showinfo('Message title','Message content')
def clicked():
messagebox.showinfo('Message title', 'Message content')
window = Tk()
window.title("Welcome")
window.geometry('350x200')
window.mainloop()
You can check what button was clicked by looking at the value
set in the resulting variable (here “res”).
12
If you click OK or yes or retry, it will return True as the value,
but if you choose no or cancel, it will return False.
The only function that returns one of three values
is the askyesnocancel function; it returns True or False or None.
window = Tk()
window.title("Welcome")
window.geometry('250x100')
var3 = IntVar()
var3.set(42) #sets defaulting value
#place widgets
spin1.grid( row = 0, column = 0)
spin2.grid( row = 1, column = 0)
spin3.grid( row = 2, column = 0)
window.mainloop()
You can specify the numbers for the Spinbox instead of using the whole range like this:
spin = Spinbox(window, values=(3, 8, 11), width=5)
Here the Spinbox widget only shows these 3 numbers: 3, 8, and 11.
13
Add a Progressbar Widget
To create a progress bar, you can use the progressbar class like this:
from tkinter.ttk import Progressbar
bar = Progressbar(window, length=200)
You can set the progress bar value like this:
bar['value'] = 70 # or using: bar.configure( value = 70)
You can set this value based on any process you want like downloading a file or completing a task.
window = Tk()
window.title("Welcome")
window.geometry('250x100')
#Place widgets
bar.grid(row = 0, column = 0)
bttn1.grid(row = 1, column = 0)
bttn2.grid(row = 2, column = 0)
window.mainloop()
14
Add an Image
PNG and GIF images can easily be added to widgets such as Labels or Buttons.
Save the picture file in to the same folder as your Python code file, then:
from tkinter import *
Modify each line to your
window = Tk() image’s file name
window.title("Welcome")
img1 = PhotoImage(file='p15-a.png')
img2 = PhotoImage(file='p15-b.png')
img3 = PhotoImage(file='p15-c.png')
myMenu = Menu(window)
myMenu.add_command(label='File')
window.config(menu=myMenu)
First, we create a menu, then we add our first label, and, finally, we assign the menu to our window.
You can add menu items under any menu by using
the add_cascade() function like this:
myMenu.add_cascade(label='File', menu=new_item)
So our code will be like this:
from tkinter import Menu
from tkinter import * #add default library last
window = Tk()
window.title("Welcome")
myMenu = Menu(window)
new_item = Menu(myMenu)
new_item.add_command( label='New')
myMenu.add_cascade( label='File', menu=new_item)
window.config(menu=myMenu)
window.mainloop()
15
This way, you can add as many menu items as you want.
You may notice a dashed line at the beginning, well, if you click that line,
it will show the menu items in a small separate window.
You can disable this feature by adding the tearoff=0 feature as seen below:
from tkinter import Menu
from tkinter import * #add default library last
To run code when clicking menu items, include the command property for the .add_command()
new_item.add_command(label='New', command=clicked)
16
Add a Notebook Widget (Tab Control)
To create a tab control, there are a few steps.
• First, we create a tab control using the Notebook class from the ttk package.
• Then, create a tab frame using the Frame class.
• Add that tab to the tab control.
• Repeat for each tab you want to add
• Pack the tab control so it becomes visible in the window.
{pack() is an alternative to the grid() for placing widgets. Just use it as is for now.}
from tkinter import ttk
from tkinter import * #add default library last
window = Tk()
window.title("Welcome")
window.geometry(“200x100”)
tab_control = ttk.Notebook(window)
tab1 = Frame(tab_control)
tab_control.add(tab1, text='First')
tab2 = Frame(tab_control)
tab_control.add(tab2, text='Second')
tab_control.pack(expand=1, fill='both')
window.mainloop()
window = Tk()
window.title("Welcome")
window.geometry("200x100")
tab_control = ttk.Notebook(window)
tab1 = Frame(tab_control)
tab2 = Frame(tab_control)
tab_control.add(tab1, text='First')
tab_control.add(tab2, text='Second')
tab_control.pack(expand=1, fill='both')
window.mainloop()
17
Hiding Notebook Tabs
It is possible to hide the navigation tabs in order to easily simulate multiple windows.
style = ttk.Style()
style.layout('TNotebook.Tab', [])
style = ttk.Style()
style.layout('TNotebook.Tab', [])
tab_control.pack(expand=1,
fill='both')
window.mainloop()
18
Spanning Across Rows and Columns
With the grid() layout, it is possible to span widgets across columns and rows using the “columnspan=”
and “rowspan=” properties. Indicate how many rows or columns to span as in the example below.
from tkinter import *
#declare widgets
bttn1 = Button(window, text="Mario")
bttn2 = Button(window, text="Luigi")
bttn3 = Button(window, text="Samus")
bttn4 = Button(window, text="Toad")
bttn5 = Button(window, text="Daisy")
bttn6 = Button(window, text="Yoshi")
#place widgets
bttn1.grid(row=0, column=0, columnspan=2, rowspan=2)
bttn2.grid(row=2, column=0)
bttn3.grid(row=2, column=1)
bttn4.grid(row=0, column=2)
bttn5.grid(row=1, column=2)
bttn6.grid(row=3, column=0, columnspan=2)
window.mainloop()
19
Multiple Frames in a Window
For organizational purposes, you may want to organize a window Frame inside another window Frame.
Then, each Frame can follow it’s own layout however you wish. This is similar to the Notebook (tabs) section.
Note that grid() placements for each Frame will start over!
from tkinter import *
#declare widgets and place onto the first frame frame1 frame2
bttn1 = Button(frame1, text="Mario")
bttn2 = Button(frame1, text="Luigi")
bttn1.grid(row=0, column=0, sticky=W+E)
bttn2.grid(row=1, column=0, sticky=W+E)
window.mainloop()
Just pass padx and pady to any widget and give them a value.
lbl1 = Label(tab1, text= 'label1', padx=10, pady=10)
20
Incomplete Topics Needing Additional Research:
Possible ideas. Use at own risk.
• background image. Placing a widget for a background may bypass the widget placement manager (grid)
bg = PhotoImage(file=”myImage.png”)
lbl_bg = Label(window, image = bg)
lbl_bg.place(x = 0, y = 0) #(0, 0) represents top left of window. Same idea pg 3
• .bind – binding keys to widgets. Right click, enter button, etc
btn = Button(...)
btn.bind(“<Button-3>”, function_name) # binds right click to button and sets function to go to
def function_name(event): #note new function needs to be passed the “event” keyword
• Photo.zoom(x,y). how does this work?
https://epydoc.sourceforge.net/stdlib/Tkinter.PhotoImage-class.html
https://tedboy.github.io/python_stdlib/generated/generated/Tkinter.PhotoImage.html#Tkinter.PhotoImage
• custom fonts. “Tkinter can only use fonts installed on the system” – no workarounds
to use, include font.ttf file with main.py.
As of 2022, school labs allows to install font by double clicking font.ttf file
21