Skip to content
Tutorials Center
My learning

Topics

Lesson 2 of 40 ยท Getting Started

Your First Tkinter Window

Create a Tkinter window and control its title, size, position, resizing, icon, transparency and closing behavior, with the geometry string explained in detail.

Every Tkinter program starts with a window. In this lesson you will create one and then shape it: give it a title, choose its size and position, decide whether the user may resize it, set an icon, and handle what happens when it closes. Almost every setting is a method on the root object, so once you know the handful below you can configure any window.

Creating the root window

Python
import tkinter as tk

root = tk.Tk()          # the main window
root.title("My First App")
root.geometry("400x300")
root.mainloop()

A program should have exactly one Tk(). If you need more windows, create tk.Toplevel(root) objects instead (chapter 5). A second Tk() creates a separate Tcl interpreter, and widgets from one cannot be used in the other, which leads to confusing errors.

The geometry string

root.geometry() takes a string with this shape:

Text
WIDTHxHEIGHT+X+Y

Width and height are in pixels, and X/Y are the position of the window's top-left corner on the screen. "400x300" sets only the size. "+100+50" sets only the position. "400x300+100+50" sets both. A negative offset such as -0+0 measures from the right or bottom edge. Calling root.geometry() with no argument returns the current string, for example "400x300+100+50".

Here is a Python function that parses a geometry string. You will meet this exact format again whenever you save a window's position or restore it on the next start.

Python Stand-in: parse a geometry string

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Centering a window on the screen

Windows open wherever the operating system chooses, which is rarely centered. To center one, ask Tk for the screen size with winfo_screenwidth() and winfo_screenheight(), then compute the offsets.

Python
import tkinter as tk

def center(window, width, height):
    screen_w = window.winfo_screenwidth()
    screen_h = window.winfo_screenheight()
    x = (screen_w - width) // 2
    y = (screen_h - height) // 2
    window.geometry(f"{width}x{height}+{x}+{y}")

root = tk.Tk()
center(root, 480, 320)
root.mainloop()

The maths is the only part you can test without a display, so here it is on its own, including a guard so a window larger than the screen is not placed off-screen.

Python Stand-in: centering maths

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Title, resizing and minimum sizes

Method What it does
root.title("Text") Sets the title bar text
root.geometry("WxH+X+Y") Size and position
root.resizable(False, False) Disallow resizing in width and height
root.minsize(300, 200) / root.maxsize(...) Limits when resizing
root.attributes("-topmost", True) Keep above other windows
root.attributes("-alpha", 0.9) Transparency from 0.0 to 1.0 (not on every platform)
root.configure(bg="white") Background color of the window
root.iconbitmap("app.ico") Window icon from an .ico file (Windows)
root.iconphoto(True, tk.PhotoImage(file="icon.png")) Window icon from a PNG, works everywhere
root.state("zoomed") / root.attributes("-fullscreen", True) Maximized or fullscreen

A common mistake is root.resizable(0, 0). It works because 0 is falsey, but False states the intent. Another is setting geometry and then wondering why the window is bigger: if you do not give a size, a window shrinks to fit its widgets (this is called geometry propagation), and if you give a size it stays that size even if widgets do not fit.

Python
import tkinter as tk

root = tk.Tk()
root.title("Settings")
root.geometry("420x260")
root.minsize(320, 200)
root.resizable(True, False)      # width can change, height cannot
root.configure(bg="#f4f1ea")
root.attributes("-topmost", True)
root.mainloop()

Understanding update(): when are sizes known?

Right after you create a window, winfo_width() returns 1 because nothing has been drawn. Tk computes sizes lazily, in idle time. Call root.update_idletasks() to flush pending layout work without handling user events, then read the real size:

Python
root = tk.Tk()
tk.Label(root, text="Some text", padx=20, pady=20).pack()
print(root.winfo_width())       # 1  (not laid out yet)
root.update_idletasks()
print(root.winfo_width())       # real width, e.g. 118
print(root.winfo_reqwidth())    # the size the widgets *ask* for

Prefer update_idletasks() over update(). update() also processes events, which can run your callbacks in the middle of other code and create hard-to-find bugs.

Closing a window

Clicking the close button destroys the window and ends mainloop(). To run code first, such as asking "Save changes?", register a handler for the WM_DELETE_WINDOW protocol:

Python
import tkinter as tk
from tkinter import messagebox

root = tk.Tk()
dirty = True

def on_close():
    if dirty and not messagebox.askyesno("Quit", "Discard unsaved changes?"):
        return                      # stay open
    root.destroy()

root.protocol("WM_DELETE_WINDOW", on_close)
tk.Button(root, text="Quit", command=on_close).pack(padx=40, pady=40)
root.mainloop()

Use root.destroy() to close. root.quit() only stops the loop and leaves the window object alive, which is useful in rare cases (for example when you want to run code after mainloop() returns) but wrong for a normal exit button.

This stand-in models the "veto the close" idea so you can see the control flow.

Python Stand-in: a close handler that can veto

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A complete first application

Putting it together: a centered, fixed-size window with a title, a label and a working Quit button.

Python
import tkinter as tk

WIDTH, HEIGHT = 360, 200

root = tk.Tk()
root.title("Welcome")
root.resizable(False, False)
x = (root.winfo_screenwidth() - WIDTH) // 2
y = (root.winfo_screenheight() - HEIGHT) // 3
root.geometry(f"{WIDTH}x{HEIGHT}+{x}+{y}")

tk.Label(root, text="Welcome to Tkinter", font=("Segoe UI", 16)).pack(pady=(40, 10))
tk.Button(root, text="Quit", command=root.destroy).pack()

root.mainloop()

The font tuple and pady pair are explained in Labels, Fonts and Colors. Next you will look inside mainloop() itself.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the geometry string '300x200+50+60' mean?

    The format is WIDTHxHEIGHT+X+Y, in pixels, with X and Y the top-left corner.
  2. 2. Why does winfo_width() return 1 right after creating a window?

    Sizes are computed during idle processing. update_idletasks() forces that without handling user events.
  3. 3. Which method should an exit button normally use to close the application?

    destroy() removes the window and its widgets. quit() just stops the loop, and Tk has no close() method.
  4. 4. How do you run code (for example a confirmation) when the user clicks the window's close button?

    The WM_DELETE_WINDOW protocol is how the window manager's close request is delivered to your code.

Summary

  • Create exactly one tk.Tk() and call mainloop() last; use Toplevel for extra windows.
  • geometry("WxH+X+Y") sets size and position; without it a window sizes itself to its content.
  • resizable, minsize, maxsize, attributes and configure adjust behaviour and looks.
  • update_idletasks() makes size queries accurate; avoid update() where you can.
  • Intercept closing with protocol("WM_DELETE_WINDOW", handler) and exit with destroy().

Next: The Event Loop