Tkinter buttons are widgets in Python Programming Tutorials that can be used to interact with the user in a graphical user interface (GUI) application. They can be used to trigger actions, such as running a function or executing a command, when they are clicked by the user.
In Tkinter, the tk.Button
class is used to create buttons. When creating a button, you can specify the button’s label, its width and height, and the command or function to be executed when the button is clicked.
Here is an example of how to create a button in Tkinter:
1 2 3 4 5 6 7 8 9 |
import tkinter as tk def button_click(): print("Button clicked!") root = tk.Tk() button = tk.Button(root, text="Click me!", command=button_click) button.pack() root.mainloop() |
In this example, a button is created with the label “Click me!” and the button_click
function is set as its command. When the button is clicked, the button_click
function will be executed and the message “Button clicked!” will be printed to the console.
You can also use lambda function, which is an anonymous function without a name, in place of a named function.
1 |
button = tk.Button(root, text="Click me!", command=lambda: print("Button clicked!")) |
In addition to the command
option, you can also use the bind()
method to associate a button with a specific event. For example, you can use the bind()
method to associate a button with the <Button-1>
event, which is triggered when the button is clicked with the left mouse button.
1 |
button.bind("<Button-1>", button_click) |
You can also change the appearance of a button by setting its bg
and fg
options to set the background and foreground color respectively, and font
option to change the font of label on the button.
Tkinter provides many options and methods for customizing buttons and responding to user input, making it a powerful tool for building GUI applications in Python.