Button Command with parameter in Tkinter

In this tutorial, I will show you how to pass parameters or arguments in the Tkinter button command.

We can do this in two different ways.

  1. Using lambda function.
  2. Using Nested function (Function inside a function)

The first one is much simpler as you just need to use lambda: before the function name and the second one is a bit hard.

But if you have a good understanding of how function works in Python then the second method will also be easy for you.

Using lambda function: Parameter passing to Tkinter button command function

We can simply add lambda: before the function calling in the command section. Take a look at the code:

import tkinter as tk
newWindow = tk.Tk()
def saruk(myVar):
    print("Button pressed")
    print(myVar.get())
newWindow.geometry("600x600+600+200")
myVar = tk.StringVar(value="codespeedy")
myButton = tk.Button(newWindow, text="Click me", command= lambda:saruk(myVar)).pack()
newWindow.mainloop()

Output in the console after pressing the button:

Button pressed
codespeedy

Using nested function to pass arguments to Tkinter button command

Take a look at the below code. I have created two functions a() and b(). And I have passed myVar as a parameter.

import tkinter as tk
newWindow = tk.Tk()
def a(parameter):
    def b():
        print("Button pressed")
        print(parameter.get())
    return b
newWindow.geometry("600x600+600+200")
myVar = tk.StringVar(value="codespeedy")
myButton = tk.Button(newWindow, text="Click me", command= a(myVar)).pack()
newWindow.mainloop()

Output in the console after pressing the button:

Button pressed
codespeedy

Leave a Reply

Your email address will not be published. Required fields are marked *