📘 CodingMarble Learn

GUI Programming with Tkinter: Windows, Widgets and Events

A GUI (graphical user interface) lets people use a program with windows, buttons and boxes instead of typing commands. In Python the built-in Tkinter library makes this easy: create a window with Tk(), add widgets such as Label, Entry and Button, arrange them with pack, grid or place, and connect each button to a function. The program then waits in mainloop() and runs your functions when events like clicks and key presses happen.

🎬 Step-by-step story

  1. tk.Tk() makes an empty window. title() gives it a name. mainloop() keeps it open and waits for the user.
  2. Widgets are objects: Label, Entry, Button, Checkbutton, Radiobutton. Each has properties like text and colour, and config() changes them.
  3. Layout managers place widgets: pack() stacks them, grid() uses rows and columns, place() uses exact x and y.
  4. An event: clicking the button calls its command function, which reads the Entry with get() and changes the Label.
  5. A Canvas game: each arrow key press is an event, and the handler moves the ball. Reach the star to score.
  6. Free play: press the buttons to fire events and watch what each handler changes.

Tip: drag the 3D scene to turn it. Use two fingers to zoom.

🤔 Common doubts, cleared

Why does my window close immediately?

Without root.mainloop() the program reaches its end and stops. mainloop keeps the window open and waits for events.

I created a Button but cannot see it. Why?

Creating a widget is not enough; it must be placed with pack(), grid() or place().

What is the difference between Entry and Text?

Entry is one line (names, numbers). Text is many lines (notes, essays). Read Entry with get(); Text with get('1.0', 'end').

Why does command=say_hi have no brackets?

You give Tkinter the function itself so it can call it later, on the click. With brackets it runs once immediately.

How does the program know which key was pressed?

root.bind links a key name like <Right> to a handler. Tkinter passes an event object whose keysym names the key.

Can I change a label after the window is open?

Yes, with config(). In free play the label changes to 'Hello, Asha!' when the button event fires.

What is a GUI and how does Tkinter start?

A GUI (graphical user interface) shows windows, buttons and text boxes. A CLI (command-line interface) only shows text. Tkinter is Python's built-in GUI library, so nothing extra needs installing.

import tkinter as tk
root = tk.Tk()            # the main window
root.title("My App")      # text in the title bar
root.geometry("400x300")  # width x height in pixels
root.mainloop()           # show it and wait for events

mainloop() is the event loop. It keeps the window open and keeps checking: did the user click? type? close? Code after mainloop() runs only when the window closes.

Widgets are objects with properties

Each widget is an object. You create it from a class and give it a parent (the window it lives in) and properties (options).

WidgetUse
Labelshows text or an image
Entryone-line text box; read it with .get()
Textmany-line text box
Buttonruns a function when clicked (command=)
Checkbuttonyes/no tick box, linked to an IntVar/BooleanVar
Radiobuttonchoose one of several, all sharing one variable
Framea box that groups other widgets
Canvasdrawing area for shapes, lines and games

Common properties: text, bg (background colour), fg (text colour), font, width. Change them later with widget.config(bg="yellow").

Messages: from tkinter import messagebox, then messagebox.showinfo("Title", "Saved!"), showwarning, showerror or askyesno (returns True/False).

Layout: pack, grid and place

A widget is invisible until a layout manager places it.

Do not mix pack and grid inside the same parent; use a Frame for each part instead.

Events, handlers and a small game

A GUI program is event-driven: it does not run top to bottom and stop. It waits for events (click, key press, mouse move) and runs a handler function for each.

def say_hi():
    name = ent.get()
    lab.config(text="Hello, " + name + "!")

btn = tk.Button(root, text="Say hi", command=say_hi)

Note: command=say_hi without brackets. With brackets the function would run at once, not on click.

For keys use bind; the handler receives an event object:

cv = tk.Canvas(root, width=400, height=300, bg="black")
ball = cv.create_oval(10, 10, 40, 40, fill="orange")
def right(event):
    cv.move(ball, 20, 0)
root.bind("<Right>", right)

A game adds a score variable, checks if two shapes overlap (with cv.coords), and uses root.after(ms, function) to move things on a timer.

Try it yourself

Type the say_hi program above into a .py file and run it. Then: (1) change the button colour with bg; (2) add a Checkbutton for 'Loud' that shows the greeting in capitals with .upper(); (3) switch from pack to grid and see the form line up.

Key formulas and definitions

Worked examples

1. Make a window titled 'Quiz' with a label 'Ready?'.

import tkinter as tk root = tk.Tk() root.title('Quiz') tk.Label(root, text='Ready?').pack() root.mainloop()

2. Add an Entry and a Button that shows the typed name in a message box.

from tkinter import messagebox ent = tk.Entry(root); ent.pack() def show(): messagebox.showinfo('Hi', 'Hello ' + ent.get()) tk.Button(root, text='OK', command=show).pack()

3. Lay out a login form: labels in column 0, entries in column 1.

tk.Label(root, text='User').grid(row=0, column=0) tk.Entry(root).grid(row=0, column=1) tk.Label(root, text='PIN').grid(row=1, column=0) tk.Entry(root, show='*').grid(row=1, column=1)

4. A Checkbutton 'Dark mode' should turn the window background black when ticked.

dark = tk.IntVar() def toggle(): root.config(bg='black' if dark.get() == 1 else 'white') tk.Checkbutton(root, text='Dark mode', variable=dark, command=toggle).pack()

5. Three Radiobuttons choose Easy / Medium / Hard. Print the choice on a button click.

level = tk.StringVar(value='Easy') for t in ['Easy', 'Medium', 'Hard']: tk.Radiobutton(root, text=t, value=t, variable=level).pack() tk.Button(root, text='Start', command=lambda: print(level.get())).pack()

6. Move a Canvas square left and right with the arrow keys.

sq = cv.create_rectangle(180, 130, 220, 170, fill='blue') root.bind('<Left>', lambda e: cv.move(sq, -10, 0)) root.bind('<Right>', lambda e: cv.move(sq, 10, 0))

Common mistakes

Practice quiz

1. Which line keeps a Tkinter window open and waiting for events?
2. Which widget is a one-line text box?
3. How do you read what the user typed in an Entry called e?
4. Which layout manager uses rows and columns?
5. A function that runs when an event happens is called a:

Practice: answer these yourself

Type or choose your answer, then press Check. Use a hint if you are stuck; the full solution appears after you answer.

Frequently asked questions

What is Tkinter in Python?

Tkinter is Python's standard library for making windows with buttons, text boxes and drawings. It comes with Python, so you only need import tkinter.

Which is better: pack, grid or place?

grid is best for forms, pack for simple stacks, place for exact positions. Many apps use Frames, each with its own manager.

Can I make games with Tkinter?

Yes, simple 2D games: draw on a Canvas, move shapes with key events and root.after timers, and keep score in variables.

Where this is taught

Canada (Ontario)Grade 12B. Software Development
RomaniaClasa a IX-aStoring data and organising code in a programming language
RomaniaClasa a IX-aStoring data and organising code in a programming language
Ukraine9 класProblem solving

Learn first

Learn next

Related lessons

All Computer Science lessons