← All lessons

Tkinter: a window with a button

Sign in · Sign up

Lesson 13.7

Tkinter is the built-in library for simple windows:

import tkinter as tk

def show():
    label.config(text="Counting")

root = tk.Tk()                    # the main window
label = tk.Label(root, text="Ready")
label.pack(pady=10)

button = tk.Button(root, text="Count", command=show)
button.pack()

root.mainloop()                   # the window loop
  • Tk() creates the main window — there is one per program;
  • pack() puts the widget into the window, without it the widget is invisible;
  • command=say_hello — without brackets: the function is called on a click, not now;
  • mainloop() keeps the window open.

A window cannot be opened in the browser, so the check puts in a little module window with the function window.button(label) — "press the button and show the label". The check gives the name name and the list of clicks clicks.

The label on the button depends on the number of clicks: the first one is Hello, <name>!, the rest are Again, <name>!. Print Now: <label> for each click.

Hint

The click counter is an ordinary number that grows on every step.

The first click gives Hello, <name>!, the rest Again, <name>!. The label is passed to window.button(label) and printed after Now:.