← Back to Python Course | Chapter 14: Advanced Python & Tools | Lesson 12 of 15

Python tkinter Introduction

What is Tkinter?

Tkinter is Python's standard-library GUI toolkit, bundled with the interpreter itself rather than needing separate installation. Like turtle graphics, it requires a real graphical display to run, though browser-based environments such as Pyodide can render Tkinter windows directly in the page.

Example: What is Tkinter?

python
import tkinter
print(tkinter.TkVersion)

Creating a Window

Every Tkinter application starts by creating a root window instance via Tk(), which represents the main application window that all other widgets get placed inside.

Example: Creating a Window

python
import tkinter
root = tkinter.Tk()
print(type(root))

The Event Loop

A newly created Tkinter window closes immediately unless you call mainloop(), which starts the event loop that keeps the window open, redraws it, and listens continuously for user interactions like clicks and keypresses until the window is closed.

Example: The Event Loop

python
import tkinter
root = tkinter.Tk()
root.after(100, root.destroy)  # auto-close so this demo doesn't hang
root.mainloop()
print("Event loop ended")

Adding Window Titles

title('My App') sets the text shown in the window's title bar, giving users a clear label identifying the application -- a small detail, but one that's easy to forget and leaves a window awkwardly unlabeled.

Example: Adding Window Titles

python
import tkinter
root = tkinter.Tk()
root.title("My App")
print(root.title())

Setting Window Dimensions

geometry(widthxheight) sets the window's initial pixel dimensions using a specific string format (like 400x300), letting you control how large the application window appears when it first opens rather than relying on a default size.

Example: Setting Window Dimensions

python
import tkinter
root = tkinter.Tk()
root.geometry("400x300")
print(root.geometry())

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.