1. tk command binding
1.1. Overview
In Tkinter, command binding allows you to connect a widget (such as a
button or slider) to a Python function. | When the user interacts with the widget (e.g., clicks a button), the linked function is executed. | This is essential for making your GUI interactive. | This is best for buttons, menus, scales, spinboxes
Many Tkinter widgets support the
command option.A callback function is called automatically when the user interacts with the widget.
The callback can then modify other widgets in the window.
1.2. Basic Syntax
The general syntax for command binding is:
widget = tk.Widget(parent, command=function_name)
Explanation:
The command option is used to bind a function to the widget.
Do NOT use parentheses () after the function name.
1.4. Example 2: Using Lambda for Arguments
Sometimes you need to pass arguments to a function.
import tkinter as tk
def greet(name):
label.config(text=f"Hello {name}.")
# Create the main window
root = tk.Tk()
root.geometry("200x100") # Set window size
root.title("Button lambda -> label Example") # Set window title
button = tk.Button(root, text="Click", command=lambda: greet("Alice"))
button.pack(pady=10)
label = tk.Label(root, text="Waiting...")
label.pack(pady=10)
root.mainloop()
Explanation:
lambda creates an anonymous function.
This allows passing arguments safely.