1

I am trying to call a function when a button clicked, When clicked it should set the value of a label.

the label initialization:

labelResult = Label(root)
labelResult.grid(row=7, column=2)

the button:

buttonCal = Button(root, command=call_result(labelResult, param1, param2)).grid(row=3, column=0)

the function:

def call_result(label_result, p1, p2):
...
...
result = ...
label_result.config(text=result)
return

When I click the button, nothing happens. The reason is the function call_result is being executed even before I click the button.

What is going wrong here ?

am using python 3.4

Kedar Kodgire
  • 482
  • 6
  • 22
Mann
  • 576
  • 1
  • 9
  • 33

1 Answers1

0

This can be done by using partial from the standard library functools, like this:

from functools import partial
call_result= partial(call_result, labelResult, param1, param2)
buttonCal = Button(root, command=call_result).grid(row=3, column=0) 

Or with lambda expression:

buttonCal = Button(root, command= lambda:call_result(labelResult, param1, param2)).grid(row=3, column=0) 

For each function object, the Tkinter interface layer registers a Tk command with a unique name. When that Tk command is called by the Button implementation, the command calls the corresponding Python function.

omri_saadon
  • 10,193
  • 7
  • 33
  • 58
  • this worked, but I wanted to know what is wrong with my previous code. – Mann Jan 29 '17 at 18:16
  • @Mann You need to pass an argument of type function to the command attribute, you passed the return value of the function instead of the function itself. In order to pass arguments to the function you need to use lambda which is a function or partial which is a function as well – omri_saadon Jan 29 '17 at 18:50