How to pass argument to a button in Tkinter

In this article, we will learn how to pass argument to a button in python:

We can actually pass a parameter to a function in 2 ways

  • Passing arguments using lambda function
  • passing arguments directly and implementing in dual function

passing arguments using lambda function

Description:

First, we create a basic window using tkinter and define a StringVar variable a. We set a to “I am Nithin”. Next, we create a function op(a) that prints the value of a. To pass a to the function when the button is clicked, we use a lambda function. The button is created with command=lambda:op(a) which ensures that when you click the button, it calls the op function with a as the argument. The output when you click the button will be:

import tkinter as tk
win=tk.Tk()
win.geometry("500x500")
a=tk.StringVar()
a.set("I am Nithin ")
def op(a):
    print(a.get())
but=tk.Button(win,text="ClickMee",command=lambda:op(a))
but.pack()
win.mainloop()

When the button is clicked the output will be :

I am Nithin

Passing argument directly and implementing in dual function

Description:

In the second method, we again use tkinter and create a StringVar variable a set to “I am Nithin “. The function op(a) now returns another function b() which, when called, prints the value of a. This dual function setup allows you to pass a directly to op, and op returns b as the command for the button. When the button is clicked, it triggers the function b() and prints:

import tkinter as tk
win=tk.Tk()
a=tk.StringVar()
a.set("I am Nithin")
def op(a):
    def b():
        print(a.get())
    return b
but=tk.Button(win,text="ClickMee",command=op(a))
but.pack()
win.mainloop()

When the button is clicked the output will be :

I am Nithin

Leave a Comment

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

Scroll to Top