Python - GUI Programming - Button Widget

Tkinter is a standard Python library used to create GUI applications. It provides a set of built-in widgets that can be used to create user interfaces such as windows, buttons, labels, menus, etc.

One of the most commonly used widgets in Tkinter is the Button widget. The Button widget is used to create a button on the interface, which can be clicked by the user to trigger an event or perform an action.

Here's a basic example of creating a Button widget in Tkinter:

import tkinter as tk
root = tk.Tk()
button = tk.Button(root, text="Click me!")
button.pack()
root.mainloop()

In this example, we first import the tkinter module and create an instance of the Tk class, which represents the main window of the application. Then, we create a Button widget using the Button class and pass the root instance as the first argument. The text parameter is used to set the text displayed on the button. Finally, we call the pack method to add the button to the main window.

When we run this program, a new window will be created with a button that says "Click me!".

Tkinter provides many other options for customizing the Button widget. For example, we can change the size, color, font, and alignment of the text on the button. We can also bind a function to the button that will be called when the button is clicked.

Here are two more examples of the Button widget in Tkinter:

Example 1: Change Label Text

import tkinter as tk
def change_text():
    label.config(text="Button clicked!")
root = tk.Tk()
root.title("Button Example")
label = tk.Label(root, text="Click the button!")
label.pack()
button = tk.Button(root, text="Click me!", command=change_text)
button.pack()
root.mainloop()

In this example, we create a Label widget that displays "Click the button!" and a Button widget that says "Click me!". When the button is clicked, the change_text function is called and the label's text is changed to "Button clicked!".

Example 2: Quit Application

import tkinter as tk
def quit_app():
    root.destroy()
root = tk.Tk()
root.title("Button Example")
label = tk.Label(root, text="Click the button to quit the application.")
label.pack()
button = tk.Button(root, text="Quit", command=quit_app)
button.pack()
root.mainloop()

In this example, we create a Label widget that gives the user instructions and a Button widget that says "Quit". When the button is clicked, the quit_app function is called and the application is destroyed, effectively closing the window.