In this, we will learn how to pass argument to tkinter button command in python. In many situations we have come up with this type of requirements. With the button widget ,we can pass arguments and data that allow the users to share .Passing the arguments to button widget allows the event to pick the arguments. It is very helpful for learning to pass the argument to tkinter button from this.
Passing argument to tkinter button command in python
Here are few steps to be followed for writing a code to pass the argument to tkinter button.
1)At first ,you need to import tkinter library and assign alias ‘tk’.
#import tkinter library and assign alias 'tk' import tkinter as tk
2)Define a function to handle the button clicks.
#Define a function to handle the button clicks def Button_Clicked(arg1, arg2): print("arg1:", arg1, "arg2:", arg2)
3)Create the main application window.
#Create the main application window window = tk.Tk()
4)Create a button widget.
#Create a button widget button = tk.Button(window, text="Click me", command=lambda:Button_Clicked("Hello", "python")) button.pack()
5)Start the main event loop.
#Start the main event loop window.mainloop()
After performing this steps you will get a output for your code as follows:
arg1: Hello arg2: python
#import tkinter library and assign alias 'tk' import tkinter as tk #Define a function to handle the button clicks def Button_Clicked(arg1, arg2): print("arg1:", arg1, "arg2:", arg2) #Create the main application window window = tk.Tk() #Create a button widget button = tk.Button(window, text="Click me", command=lambda:Button_Clicked("Hello", "python")) button.pack() #Start the main event loop window.mainloop()
OUTPUT:
arg1: Hello arg2: python