0% found this document useful (0 votes)
18 views21 pages

Tkinter Starter v8 Incomplete

This tutorial provides a comprehensive guide on developing graphical user interfaces (GUIs) in Python using the Tkinter package. It covers the creation of various widgets such as labels, buttons, entry fields, checkboxes, and radio buttons, along with their properties and event handling. The tutorial assumes a basic understanding of Python and is structured to help users build their first GUI application step-by-step.

Uploaded by

782610
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views21 pages

Tkinter Starter v8 Incomplete

This tutorial provides a comprehensive guide on developing graphical user interfaces (GUIs) in Python using the Tkinter package. It covers the creation of various widgets such as labels, buttons, entry fields, checkboxes, and radio buttons, along with their properties and event handling. The tutorial assumes a basic understanding of Python and is structured to help users build their first GUI application step-by-step.

Uploaded by

782610
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Python GUI Examples (Tkinter Tutorial) v1.

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.

Create Your First GUI Application


First, we will import the Tkinter package and create a window and set its title:
from tkinter import *

window = Tk()
window.title("Welcome")

window.mainloop()

The result will look like this:

Awesome! Our application works!

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.

Create a Label Widget Set Widget Width (not just Labels)


To add a label to our previous example, we will create a Most widgets support specifying the size or width when
label using the label class like this: created.

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()

And this is the result:

Set Label Font Size


You can set the label font so you can make it bigger and maybe bold.
You can also change the font style.
To do so, you can pass the font() parameter like this:
lbl = Label(window, text="Hello", font=("Arial Bold", 50))

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.

Adding a Button Widget


Let's start by adding the button to the window.
The button is created and added to the window in the same way as the label:
btn = Button(window, text="Click Me")
btn.grid(column=1, row=0)
So our window will be like this:
from tkinter import *
Widgets can be placed with .grid()
window = Tk() based on rows and columns.
window.title("Welcome") It starts with row=0 and column=0
window.geometry('350x200')
on the top left.
lbl = Label(window, text="Hello")
lbl.grid(row=0, column=0)
Columns
btn = Button(window, text="Click Me")
btn.grid(row=0, column=1)
Rows
window.mainloop()

The result looks like this:

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")

Note: these attributes may not


display properly with Apple
products but they should work
properly in the computer lab.
Consider using a similar attribute
“highlightbackground=”

Now, if you tried to click on the button, nothing happens because the click event of the button isn't written yet.

Handle Button Click Event


We will write a separate function to execute for each button we add.
This is the logic of the program, DO NOT create new widgets in these functions!!!!:
def clicked():
lbl.configure(text="Button was clicked !!")

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!

Now the full code will be like this:


from tkinter import * These must match!
If you want a second button to do
def clicked(): something else, we will add another
different function.
lbl.configure(text="Button was clicked !!") See ScrolledText example p11

#Main Program
window = Tk()
window.title("Welcome")
window.geometry('350x200')

lbl = Label(window, text="Hello")


lbl.grid(row=0, column=0)

btn = Button(window, text="Click Me", command = clicked)


btn.grid(row=0, column=1)

window.mainloop()
4
And when we click the button, the result, as expected, looks like this:

Cool!

Get Input Using Entry Class (Tkinter Textbox)


In the previous Python GUI examples, we saw how to add simple widgets, now let's try getting the user input
using the Tkinter Entry() class (Tkinter textbox). Note the grid() parameter for “column” gets changed to place
different widgets in different places.
Notice that code in the “def something(): ” section(s) may update existing widgets.
You can create new regular variables in the “def something(): “ section(s), but

!
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

So our window will be like this:


from tkinter import *

def clicked():
lbl.configure(text="Button was clicked !!")

window = Tk() never


window.title("Welcome") never
window.geometry('350x200') define new
widgets in
lbl = Label(window, text="Hello") functions!
lbl.grid(row=0, column=0) !!!
txt = Entry(window,width=10)
txt.grid(row=0, column=1)
btn = Button(window, text="Click Me", command=clicked)
btn.grid(row=0, column=2)

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')

lbl = Label(window, text="Hello")


lbl.grid(row=0, column=0)
txt = Entry(window,width=10)
txt.grid(row=1, column=0)
btn = Button(window, text="Click Me", command=clicked)
btn.grid(row=1, column=1)

txt.focus() .focus() will set the cursor into the


Entry box so you can start typing
window.mainloop()

6
Run the above code and check the result:

Awesome!

Keeping a Running Score


Let’s say you want to keep track of something in a variable that’s not a Label or another widget.
In order for your Button function to be able to access a variable created in the Main part of the program,
you will need to add a “global” indicator to tell python to access that variable.
If you don’t, python will create a “local” variable of the same name for the function that is different
than the one from Main. This is based on variable scope and trying to access a non tkinter variable.
In short, for your Button functionality to access variables from the Main Program, use “global”

from tkinter import *

def addMe():

global counter #want to use counter from Main

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')

lbl = Label(window, text="Hello")


lbl.grid(row=0, column=0)
txt = Entry(window,width=10)
txt.grid(row=1, column=0)
btn = Button(window, text="Add Me", command=addMe)
btn.grid(row=1, column=1)

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())

#create main window


window = Tk()
window.title("Welcome")
window.geometry('350x200')

#create combo box


combo = Combobox (window)
combo['values'] = [1,2,3,4,5, "Text"] #adds values as a list
combo.current(1) #set the selected item.
combo.grid(row=0, column = 0)

lbl = Label (window) #adds empty Label to window


lbl.grid(row=1, column = 0, sticky=W) #align text to West (left) side

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"

#empty out all the text in the Label, then update it


results_txt.delete(0.0, END) #(where to start, to END)
results_txt.insert(0.0, likes) #(where to insert, text to insert)

#create main window


window = Tk()
window.title("Welcome")
window.geometry('400x200')

#create variable to link to check button


chk1_state = BooleanVar()
chk1_state.set(False) #set check state
chk2_state = BooleanVar()
chk2_state.set(False) #set check state
chk3_state = BooleanVar()
chk3_state.set(False) #set check state

#create check button, connect it's "var" with a program variable


chk1 = Checkbutton (window, text = "A New Hope",
var = chk1_state, command = update_text)
chk1.grid( row = 0, column = 0, sticky=W) See page 18
chk2 = Checkbutton (window, text = "The Empire Strikes Back", for “sticky=”
var = chk2_state, command = update_text)
chk2.grid( row = 1, column = 0, sticky=W)
chk3 = Checkbutton (window, text = "Return of the Jedi",
var = chk3_state, command = update_text)
chk3.grid( row = 2, column = 0, sticky=W)

results_txt = Text( window, width=50, height=5, wrap=WORD)


results_txt.grid( row=5, column=0, columnspan=4)

window.mainloop()

Set the Check State of a Checkbutton


Here we create a variable of type BooleanVar() which is not a standard Python variable, it's a Tkinter
variable, and then we pass it to the Checkbutton class to set the check state as the bolded lines in the above
example. This lets us access the widget values directly with the chk1_state variable.
Other useful Tkinter variables are IntVar() and StringVar().

You can set the Boolean value to False to make it unchecked.

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

These examples give the same result as the BooleanVar().

Add Radio Button Widgets


To add radio buttons, you can use the RadioButton class:
rad1 = Radiobutton(window,text='First', value=1)
Note that you should set the value for every radio button with a different value, otherwise they won't work.
To get the currently selected radio button or the radio button's value,
you can pass the variable parameter to the radio buttons and later you can get its value.
from tkinter import *

def clicked():
print(selected.get())

window = Tk()
window.title("Welcome")

selected = IntVar()

rad1 = Radiobutton(window,text='First', value=1, variable=selected)


rad2 = Radiobutton(window,text='Second',value=2, variable=selected)
rad3 = Radiobutton(window,text='Third', value=3, variable=selected)
btn = Button(window, text="Click Me", command=clicked)
rad1.grid(row=0, column=0)
rad2.grid(row=0, column=1)
rad3.grid(row=0, column=2)
btn.grid(row=0, column=3)

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.

You can also set a command of any of these radio buttons


to a specific function, so if the user clicks on any one of them,
it runs the function code.
This is an example:
def clicked():
# Do what you need

rad1 = Radiobutton(window,text='First', value=1, command=clicked)

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.

Set Scrolledtext Content


To set scrolledtext content, you can use the insert method as was done for the Text Widget earlier like this:
txt.insert(INSERT,'Your text goes here')

Delete/Clear Scrolledtext Content


To clear the contents of a scrolledtext widget, you can use the delete method
(also same as the Text Widget) like this:
txt.delete(0.0,END)

The result as you can see:

from tkinter import scrolledtext


from tkinter import * #add default library last

#define function when button is clicked


def click_insert():
txt.insert(INSERT, "Nintendo is awesome\n")

def click_delete():
txt.delete(0.0, END)

#Main program
#create main window
window = Tk()
window.title("Welcome")
window.geometry('350x250')

#create scrolledtext widget


txt = scrolledtext.ScrolledText( window, width = 40, height = 10)
txt.grid (row=0, column = 0)

#create buttons
btn1 = Button( window, text = "Click to Add", command = click_insert)
btn2 = Button( window, text = "Click to Del", command = click_delete)

btn1.grid( row = 1, column = 0)


btn2.grid( row = 2, column = 0)

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')

Let's show a message box when the user clicks a button.


from tkinter import messagebox
from tkinter import * #add default library last

def clicked():
messagebox.showinfo('Message title', 'Message content')

window = Tk()
window.title("Welcome")
window.geometry('350x200')

btn = Button(window,text='Click here', command=clicked)


btn.grid(row=0, column=0)

window.mainloop()

When you click the button, an informative message


box will appear.

Show Warning and Error Messages


You can show a warning message or error message the same way. The only thing that needs to be changed is the
messagebox function
messagebox.showwarning('Message title', 'Message content') #shows warning message
messagebox.showerror('Message title', 'Message content') #shows error message

Show Ask Question Dialogs


To show a yes/no message box to the user, you can use one of the following messagebox functions:
from tkinter import messagebox
res = messagebox.askquestion('Message title','Message content')
res = messagebox.askyesno('Message title','Message content')
res = messagebox.askyesnocancel('Message title','Message content')
res = messagebox.askokcancel('Message title','Message content')
res = messagebox.askretrycancel('Message title','Message content')

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.

The following example shows all of these messageboxes:


(source code available on class website)

Add a SpinBox (Numbers Widget)


To create a Spinbox widget, you can use the Spinbox class like this:
spin = Spinbox(window, from_=0, to=100)
Here we create a Spinbox widget and we pass the from_ and to parameters
to specify the numbers range for the Spinbox.
Also, you can specify the width of the widget using the width parameter:
spin = Spinbox(window, from_=0, to=100, width=5)
Check the complete example:
from tkinter import *

window = Tk()
window.title("Welcome")
window.geometry('250x100')

var3 = IntVar()
var3.set(42) #sets defaulting value

spin1 = Spinbox( window, from_ = 0, to = 100, width = 5)


spin2 = Spinbox( window, values = [3, 8, 11], width = 5)
spin3 = Spinbox( window, from_ = 0, to = 100, width = 5, textvariable = var3)

#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.

Set a Default Value for Spinbox


To set the Spinbox default value, you can pass the value to the textvariable parameter like this:
var = IntVar()
var.set(42)
spin = Spinbox(window, from_=0, to=100, width=5, textvariable=var)
Now, if you run the program, it will show 42 as a starting value for the Spinbox.

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.

Change Progressbar Colour


Changing the Progressbar colour is a bit tricky.
First, we will create a style and set the background colour and finally set the created style to the Progressbar.
Check the following example:
from tkinter.ttk import Progressbar
from tkinter import ttk
from tkinter import * #add default library last

#define commands for buttons


def bttn_add():
if (int(bar["value"]) < 100):
bar["value"] = int(bar["value"]) + 1
def bttn_del():
if (int(bar["value"]) > 0):
bar["value"] = int(bar["value"]) - 1

window = Tk()
window.title("Welcome")
window.geometry('250x100')

style = ttk.Style() #create style


style.theme_use("default")
style.configure("black.Horizontal.TProgressbar", background = "black")
bar = Progressbar( window, length = 200, style="black.Horizontal.TProgressbar")
bar["value"] = 70

bttn1 = Button(window, text = "Add", command = bttn_add)


bttn2 = Button(window, text = "Del", command = bttn_del)

#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')

lbl = Label( window, image = img1)


lbl.grid(row=0, column=0)
To change a picture in a function,
bttn1 = Button( window, image = img2) three steps are needed:
bttn1.grid(row=0, column=1)

bttn2 = Button( window, image = img3) 1) define the image


bttn2.grid(row=0, column=2) 2) configure existing widget with image
3) activate changes
window.mainloop()
#example:
img = PhotoImage(file=’x.png’)
lbl.configure(image=img)
lbl.image=img
Menu Bar
To add a menu bar, you can use the menu class like this:
from tkinter import Menu

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

#create main window


window = Tk()
window.title("Welcome")
window.geometry('200x100')

#create menu to add to window


myMenu = Menu(window)

#Start defining all items for the menu


#add first menu list to add to menu
first_menu = Menu(myMenu)
first_menu.add_command( label = "One_a")
first_menu.add_separator()
first_menu.add_command( label = "One_b")
myMenu.add_cascade( label = "One", menu = first_menu)

#adds second menu list beside first menu list


second_menu = Menu(myMenu, tearoff = 0) #do not allow tear off (dotted)
second_menu.add_command( label = "Two_a")
myMenu.add_cascade (label = "Two", menu = second_menu)

#adds nested menu under second menu


nested_menu = Menu(second_menu)
nested_menu.add_command( label = "Two_b_nest-1")
nested_menu.add_command( label = "Two_b_nest-2")
second_menu.add_cascade( label = "Two_b", menu = nested_menu)

#add configured menu to main window


window.config( menu = myMenu)
window.mainloop()

To run code when clicking menu items, include the command property for the .add_command()
new_item.add_command(label='New', command=clicked)

To see a code example, download “p16-Menubar-command.py” from the class website.

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()

Add Widgets to Notebooks


After creating tabs, you can put widgets inside these tabs by assigning the parent property to the desired tab.
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)
tab2 = Frame(tab_control)
tab_control.add(tab1, text='First')
tab_control.add(tab2, text='Second')

lbl1_1 = Label(tab1, text= 'Label 1 on the First tab')


lbl1_1.grid(row=0, column=0)
lbl2_1 = Label(tab2, text= 'Another Label, Second tab')
lbl2_1.grid(row=0, column=0)

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', [])

Switch between Notebook Tabs tab_control = ttk.Notebook(window)


tab1 = Frame(tab_control)
Hidden tabs are more useful when you can use buttons tab2 = Frame(tab_control)
to click between different tabs. The following example tab_control.add(tab1, text='First')
updates the previous example with hidden tabs and tab_control.add(tab2, text='Second')
clicking to switch between them.
lbl1_1 = Label(tab1, text= 'Label 1
from tkinter import ttk on the First tab')
from tkinter import lbl1_1.grid(row=0, column=0)
btn_tab1 = Button(tab1, text='to 2',
def btn_1to2(): command=btn_1to2)
tab_control.select(tab2) btn_tab1.grid(row=1, column=0,
sticky=N+S+W+E)
def btn_2to1():
tab_control.select(tab1) lbl2_1 = Label(tab2, text= 'Another
Label, Second tab')
window = Tk() lbl2_1.grid(row=0, column=0)
window.title("Welcome") btn_tab2 = Button(tab2, text='to 1',
window.geometry("200x100") command=btn_2to1)
btn_tab2.grid(row=1, column=0,
sticky=N+S+W+E)

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 *

#create main window


window = Tk()
window.title("Welcome")

#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()

Stretching to Fill Columns and Rows


The above example shows how to span widgets across columns and rows with .grid(), but as seen with
buttons “Mario” and “Yoshi”, it does not fill the columns and rows by default. Adding the “sticky=” option
when placing widgets can tell the widget to align to any of the North, South, West, or East region of the cell with
“sticky=N” or “sticky=W”, etc.
Multiple options can even be combined with “sticky=W+E”, “sticky=N+S+W+E”, or whatever you like.
Only the following two lines from the above example were updated to create the following window:

bttn1.grid(row=0, column=0, columnspan=2, rowspan=2, sticky=N+S+W+E)

bttn6.grid(row=3, column=0, columnspan=2, sticky=W+E)

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 *

#create main window


window = Tk()
window.title("Welcome")
window.geometry('200x100')

#add Frames to window


frame1 = Frame(window)
frame1.grid(row=0, column=0)
frame2 = Frame(window)
frame2.grid(row=0, column=1)

#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)

#declare widgets and place onto the second frame


bttn21 = Button(frame2, text="Peach")
bttn22 = Button(frame2, text="Daisy")
bttn21.grid(row=0, column=0, sticky=W+E)
bttn22.grid(row=1, column=0, sticky=W+E)

window.mainloop()

Add Spacing Around Widgets (Padding)


You can add space padding around your widgets to make it look well organized
using the padx and pady properties. Padx pads around the horizontal edges, Pady pads around the vertical .

Just pass padx and pady to any widget and give them a value.
lbl1 = Label(tab1, text= 'label1', padx=10, pady=10)

This will add 10 pixels of empty space around the Label.


For the code of the following example, see the course website.

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

• Additional resources and reference.


Python and Tkinter: https://python-course.eu/tkinter

Complete book of python and tkinter (copyright no share)


https://python-course.eu/books/bernd_klein_python_tutorial_letter.pdf

21

You might also like