Button Command in Tkinter
Tkinter is a popular GUI toolkit for Python that allows you to create graphical user interfaces. One of the most commonly used widgets in Tkinter is the Button widget, which allows you to create buttons that perform a specific command when clicked.
Button Command Function
In Tkinter, you can specify a command for a Button widget using the command
attribute. When the button is clicked, the command is executed. For example:
import tkinter as tk
def on_button_click():
print("Button clicked")
root = tk.Tk()
button = tk.Button(root, text="Click me", command=on_button_click)
button.pack()
root.mainloop()
In this example, a Button widget is created with the text “Click me” and the on_button_click
function is specified as the command. When the button is clicked, the function prints “Button clicked” to the console.
Button Command Function With Arguments
Sometimes, you may want to pass arguments to the command function when a button is clicked. One way to achieve this is using a lambda function. Here’s an example:
import tkinter as tk
def on_button_click(name):
print(f"Hello, {name}")
root = tk.Tk()
button = tk.Button(root, text="Say Hello", command=lambda: on_button_click("John"))
button.pack()
root.mainloop()
In this example, a Button widget is created with the text “Say Hello” and a lambda function is used to pass the argument “John” to the on_button_click
function when the button is clicked.
By using the command
attribute with a lambda function, you can create buttons in Tkinter that perform specific commands with arguments when clicked.
💻 My Source Codes: https://www.buymeacoffee.com/fabiomusanni/extras
⬇ LEARN ON THE BEST LEARNING PLATFORMS (LINKS BELOW) 😉💪 ⬇
☕ Buy me a coffee: https://www.buymeacoffee.com/fabiomusanni
❤ Support me monthly: https://www.patreon.com/FabioMusanni
😍 One-off donation: https://www.paypal.me/FabioMusanni/
SKILLSHARE
(Python, Web Dev, UI/UX Design, Music, Art, Animation and a lot more)
🔗 https://skillshare.eqcm.net/5gxzD2 (Affiliate)
DATACAMP
(Python, ChatGPT, SQL, Power BI, and a lot more)
🔗 https://datacamp.pxf.io/vN1bDj (Affiliate)
COURSERA PYTHON
(For beginners, Data Science, Data Analysis, AI, Cybersecurity and a lot more):
🔗 https://imp.i384100.net/k0Nk60 (Affiliate)
COURSERA WEB DEVELOPMENT
(Full Stack, Front-End, Back-End, Web Design and a lot more):
🔗 https://imp.i384100.net/EKWxBW (Affiliate)
Thank you for the support!❤
🎥All videos about Tkinter: https://www.youtube.com/playlist?list=PLs8qUrmRvaR1M1AatvOUy3eF_yoVEBJXk
🎥All my videos about Python: https://www.youtube.com/playlist?list=PLs8qUrmRvaR0IT4IwJl-LSweAdACW-yLK
Bravo!!🙏🙏👌👌🖖🖖🖖🖖🖖💖