Pass argument to a Button command function in Tkinter
In this Tkinter tutorial, we will learn how to pass an argument to a button command function.
We can pass arguments in two different ways.
- Using lambda
- Using nested function
Pass argument to button command using lambda
This is the easiest way to do this.
We just need to write labda: just before declaring the function in command parameter of our Tkinter button just like this:
command= lambda: functionName(argument)
Let’s check through a basic example:
import tkinter as tk newWindow = tk.Tk() myButton = tk.Button(newWindow, text="Click me", command= lambda: print("HI")) myButton.pack() newWindow.mainloop()
Output:
If you click on the button, you can see HI
will be printed in the console.
Here, print is our function and HI is an argument.
Now let’s create our own custom function and see how it goes.
import tkinter as tk newWindow = tk.Tk() def codespeedy(para1): print(para1) arg1 = "Hi there" myButton = tk.Button(newWindow, text="Click me", command= lambda: codespeedy(arg1)) myButton.pack() newWindow.mainloop()
Here, arg1
is an argument that I am passing to the function codespeedy()
. And inside the codespeedy()
function there is a parameter which is para1.
In this way, we can easily pass any argument to our Tkinter button command.
Pass argument to button command using nested function in Tkinter
Now, I will be removing the lambda and using nested function.
import tkinter as tk newWindow = tk.Tk() def codespeedy(para1): def childFunction(): print(para1) return childFunction arg1 = "Hi there" myButton = tk.Button(newWindow, text="Click me", command= codespeedy(arg1)) myButton.pack() newWindow.mainloop()
It will work in the same way.
Tip for our viewers: Whenever working in Tkinter you should use .StringVar()
instead of directly storing string values in a variable. The good practice is this:
import tkinter as tk newWindow = tk.Tk() def codespeedy(para1): def childFunction(): print(para1.get()) return childFunction arg1 = tk.StringVar(value="Hi there") myButton = tk.Button(newWindow, text="Click me", command= codespeedy(arg1)) myButton.pack() newWindow.mainloop()
You have to use variable.get() to return the value.
If you want the video tutorial you can check it:
Leave a Reply