Tkinter is the standard Python library for creating graphical user interfaces (GUIs) and the Button
class is a widget provided by Tkinter that is used to create buttons in a GUI. The Button
class is typically used to create a command button that the user can click to initiate an action or event. You can create a button in Tkinter by instantiating the Button
class and specifying the master
window, the button’s text
or label, and any other desired options such as the command
or function that should be called when the button is clicked. Here’s an example of creating a button in Tkinter:
1 2 3 4 5 |
from tkinter import * root = Tk() button = Button(root, text="Click Me!", command=my_function) button.pack() root.mainloop() |
This creates a button with the label “Click Me!” that, when clicked, calls the function my_function
.
Here is an example of how you might use the command
option to implement the click functionality for a button in Tkinter:
1 2 3 4 5 6 7 8 9 |
from tkinter import * def my_function(): print("Button clicked!") root = Tk() button = Button(root, text="Click Me!", command=my_function) button.pack() root.mainloop() |
In this example, when the button is clicked, it will call the my_function
which will print “Button clicked!” in the console.
Run the complete code and this will be the result
You can also use the bind
method to bind a button click to a function, for example:
1 2 3 4 5 6 7 8 9 10 |
from tkinter import * def my_function(event): print("Button clicked!") root = Tk() button = Button(root, text="Click Me!") button.bind("<Button-1>", my_function) button.pack() root.mainloop() |
This will also print the “Button clicked!” when the button is clicked by left mouse button.
Additionally, you can use the config
method to change the button’s properties such as the text or background color after it has been created.
1 |
button.config(text="New Text") |
You can also use configure
method, both works similar.
1 |
button.configure(text="New Text") |
You can use the above methods to customize and control your button as per your requirement.