Home / Library / Tkinter / Introduction / Hello, tkinter

Hello, tkinter

The traditional first program, in the form it takes in Python 3.

Hello

import tkinter as tk

root = tk.Tk()
label = tk.Label(root, text="Hello, world")
label.pack()
root.mainloop()

Four things happen.

In Python 2 the module was Tkinter with a capital T. In Python 3 it is tkinter. That rename is why so many old examples fail on the first line.

Hello again, as a class

Anything beyond a single window is easier as a class, because the widgets and the methods that respond to them then live together.

import tkinter as tk
from tkinter import ttk

class Application(ttk.Frame):
    def __init__(self, parent):
        super().__init__(parent, padding=12)
        self.grid(sticky="nsew")
        self.build()

    def build(self):
        self.message = tk.StringVar(value="Hello, world")
        ttk.Label(self, textvariable=self.message).grid(row=0, column=0, pady=6)
        ttk.Button(self, text="Change", command=self.change).grid(row=1, column=0)
        ttk.Button(self, text="Quit", command=self.winfo_toplevel().destroy).grid(row=2, column=0, pady=6)

    def change(self):
        self.message.set("Hello again")

root = tk.Tk()
root.title("Example")
Application(root)
root.mainloop()

Three habits worth picking up from this.

Passing arguments to a callback

ttk.Button(self, text="Red", command=lambda: self.pick("red")).grid(row=3, column=0)

Careful inside loops. A lambda that closes over the loop variable sees its final value, so bind it as a default argument instead:

for colour in ("red", "green", "blue"):
    ttk.Button(self, text=colour, command=lambda c=colour: self.pick(c)).grid()

Related