Ivan's Homepage

Creating GUI with Tkinter

Creating a GUI with elementor is super easy!

Step 1: Import the TKinter library

from tkinter import *

Step 2: Make a window

window = Tk() 
window.title("Welcome to the Loh Family app")

#To set the window size, use the following code:

Step 3: Add widgets to the window

lbl = Label(window, text="Hello")
#With formatting
lbl = Label(window, text="Hello", font=("Arial Bold", 50))
btn = Button(window, text="Click Me")
#Button with formatting
btn = Button(window, text="Click Me", bg="orange", fg="red")
#Text entry (Textbox)
txt = Entry(window,width=10)
#Disable entry
txt = Entry(window,width=10, state='disabled')

Step 4: Set the position of the widgets


#Using Grid
btn.grid(column=1, row=0)

#Using Place
btn.place(x=5, y=3)

#Using Pack


Grid arranges the window into a table-like grid and places elements in it.



Place allows you to place the widget anywhere in the window by specifying the X and Y positions.


Pack automatically packs the widget into the available space. However, you can request python to pack it based on your preferred alignment, e.g. pack to bottom, pack to top, or left or right. 

Step 5: Write functions to handle events (e.g. button click)


#First add the command to the button
btn = Button(window, text="Click Me", command=clicked)

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

In the example above, the function “clicked()”will be called when the user pressed the button. The “Configure”function is used to change the content of the label when the button is clicked. 

For full sample code, click the button below


Today, you will design a simple BMI calculator based on what you’ve learned previously. You can refer to the previous BMI calculator example in lesson 1. Click the button below to access lesson 1.

Bonus: Adding images

# Import required libraries from tkinter 
from PIL import ImageTk, Image
# Create an instance of tkinter window

win = Tk()
# Define the geometry of the window
frame = Frame(win, width=600, height=400)
frame.place(anchor='center', relx=0.5, rely=0.5)
#Create an object of tkinter ImageTk
img = ImageTk.PhotoImage(Image.open("forest.jpg"))
# Create a Label Widget to display the text or Image
label = Label(frame, image = img)

Leave a Comment

Your email address will not be published. Required fields are marked *