Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 40 ยท Widgets Basics

Tkinter Buttons and Command Callbacks

Create Tkinter buttons, pass arguments to callbacks with lambda and functools.partial, avoid the late-binding loop bug, disable buttons and style them with images.

A Button runs a function when clicked. That function is a callback: you hand it to Tk now and Tk calls it later. Getting callbacks right (when they run, how to give them arguments, how to avoid the famous loop bug) is the most important skill in this lesson, and it applies to every widget with a command option.

A basic button

Python
import tkinter as tk

def say_hello():
    print("Hello!")

root = tk.Tk()
tk.Button(root, text="Greet", command=say_hello).pack(padx=40, pady=30)
root.mainloop()

Notice command=say_hello with no parentheses. Writing command=say_hello() would call the function while building the window and pass its result (None) to Tk, so the button would do nothing when clicked. You give Tk the function itself; Tk adds the parentheses at click time.

Common button options

Option Meaning
text Caption
command Function to call on click
state "normal", "active" or "disabled"
width, height Size in characters (pixels with an image)
bg, fg, activebackground, activeforeground Colors normally and while pressed
relief, bd Border style and thickness
font, padx, pady As for labels
image, compound Image button, with optional text
underline Index of the letter to underline as a keyboard hint
default "active" marks the default button (used by dialogs)
repeatdelay, repeatinterval Auto-repeat while held (milliseconds)
takefocus Whether Tab focuses it

On macOS the classic tk.Button ignores bg because the system draws its own look. If you need cross-platform styling, use ttk.Button and a style (chapter 7), or build a clickable Label.

Passing arguments to a callback

Tk calls your command with no arguments. To send some, wrap the call.

With lambda:

Python
tk.Button(root, text="Red",  command=lambda: set_color("red")).pack()
tk.Button(root, text="Blue", command=lambda: set_color("blue")).pack()

With functools.partial:

Python
from functools import partial
tk.Button(root, text="Green", command=partial(set_color, "green")).pack()

Both produce a function that takes no arguments and calls set_color with the value baked in.

The late-binding trap in loops

This is the bug nearly everyone hits. You build several buttons in a loop:

Python
for name in ["red", "green", "blue"]:
    tk.Button(root, text=name, command=lambda: set_color(name)).pack()

Every button ends up setting blue. A lambda looks up the variable name when it is called, not the value it had when the lambda was created, and by the time you click, the loop has finished with name == "blue". The stand-in below reproduces it in plain Python, so you can see the problem and three fixes.

Python Stand-in: the loop-lambda bug and its fixes

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.

Prefer partial or the default-argument trick (lambda n=name: ...). They are short and make the capture explicit.

Do not forget what a callback returns

Whatever your callback returns is ignored. If you need data back, store it on self, in a variable, or in a widget. For example, an "Add" button can read an entry, compute a result and write it into a label.

Python
import tkinter as tk

def add():
    try:
        total = float(a.get()) + float(b.get())
        result.config(text=f"= {total:g}", fg="black")
    except ValueError:
        result.config(text="Enter two numbers", fg="red")

root = tk.Tk()
root.title("Adder")
a = tk.Entry(root, width=8); a.grid(row=0, column=0, padx=6, pady=8)
tk.Label(root, text="+").grid(row=0, column=1)
b = tk.Entry(root, width=8); b.grid(row=0, column=2, padx=6)
tk.Button(root, text="Add", command=add).grid(row=0, column=3, padx=6)
result = tk.Label(root, text="")
result.grid(row=1, column=0, columnspan=4, pady=(0, 8))
root.mainloop()

The conversion logic is worth keeping separate from widgets so you can test it. Here is that logic, with the failure cases:

Python Stand-in: callback logic with error handling

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.

Disabling and enabling

A disabled button looks grey and ignores clicks. Use it to prevent double-submit or to enforce "fill in the form first":

Python
button = tk.Button(root, text="Send", command=send)
button.config(state="disabled")
...
button.config(state="normal")

A very common pattern is to disable the button at the start of a long job and re-enable it at the end, so the user cannot start it twice. Remember that a callback which runs for seconds freezes the window anyway; see The Event Loop.

A disabled button also loses its hover and focus feedback; if you need it to look disabled but still show a tooltip, you will have to use a custom label.

Buttons with images

Python
icon = tk.PhotoImage(file="save.png")
button = tk.Button(root, image=icon, text=" Save", compound="left", command=save)
button.image = icon            # keep the reference
button.pack()

compound can be "left", "right", "top", "bottom" or "center" and says where the image goes relative to the text.

Keyboard shortcuts for buttons

Buttons can be activated with Space when focused. To give a button a global shortcut, bind a key on the root window and call the button's invoke() method, which behaves exactly like a click (and respects state):

Python
root.bind("<Return>", lambda event: ok_button.invoke())
root.bind("<Escape>", lambda event: cancel_button.invoke())

Note that a bound function receives an event argument, unlike command= functions. That is why those lambdas take event. Chapter 4 explains events in full.

Flash, toggle and other tricks

  • button.flash() briefly alternates colors to draw attention.
  • A "toggle" button can swap its own text in the callback: b.config(text="Stop" if running else "Start").
  • Use one function for many buttons by passing a different argument, as with the calculator keypad below.

This stand-in builds a keypad's logic with one handler and partial:

Python Stand-in: one handler, many buttons

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.

The stand-in uses eval only on a restricted string for the sake of demonstration; in a real calculator, prefer a small parser, because eval on user input is unsafe.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is wrong with Button(root, text='Go', command=run())?

    With parentheses the function runs at creation time. Pass run itself so Tk can call it on click.
  2. 2. Buttons are created in a loop with command=lambda: show(i). Why do all of them show the last i?

    Closures capture variables, not values. Use lambda i=i: show(i) or functools.partial(show, i).
  3. 3. How do you make a button ignore clicks?

    state='disabled' keeps the button visible but inactive.
  4. 4. What does button.invoke() do?

    invoke() calls the command, which makes it handy for keyboard shortcuts.

Summary

  • command= takes a function without parentheses; Tk calls it with no arguments.
  • Add arguments with lambda (use a default argument in loops) or functools.partial.
  • Return values from callbacks are ignored; update widgets or self instead.
  • state="disabled" stops clicks; invoke() triggers a click from code or a key binding.
  • Keep a reference to button images and keep the logic in plain functions you can test.

Next: Tkinter Variables