-3

What I need is to attach a function to a button that is called with a parameter. When I write the code as below however, the code is executed once when the button is created and then no more. Also, the code works fine if I get rid of the parameter and parentheses when I declare the function as an attribute of the button. How can I call the function with a parameter only when the button is pressed?

from Tkinter import *

root =Tk()

def function(parameter):
    print parameter

button = Button(root, text="Button", function=function('Test'))
button.pack()

root.mainloop()
Jonas
  • 1,473
  • 2
  • 13
  • 28

1 Answers1

0

The solution is to pass the function as a lambda:

from Tkinter import *

root =Tk()

def callback(parameter):
    print parameter

button = Button(root, text="Button", command=lambda: callback(1))
button.pack()

root.mainloop()

Also, as @nbro already correctly pointed out, the button attribute is command, not function.