-1

I have made a function called get_data['name']. This function gets a string('name' for example) and the output is an array of number.

I have made few button with tkinter that looks like this:

# A Button
A_Button = Button(GUI, image=A_Im, command=get_data('a_name'))
A_Button.grid(column=0, row=1)

# C Button
C_Button = Button(GUI,image=C_Im,command=get_data('c_name'))
C_Button.grid(column=0, row=2)

# D_Button
D_Button = Button(GUI, image=D_Im, command=get_data('d_name'))
D_Button.grid(column=0, row=3)

However, when i run the code, It executes the function get_data for every button, while i wanted it to work only when i click the specific button.

How can i make it work only at click?

Thank you.

Ben
  • 1,737
  • 2
  • 30
  • 61

1 Answers1

1

The problem is that the way you're assigning a value to the Button's command argument, will first immediately call the get_data function. This is because you're writing it as a regular function call. In the end you end up assigning the return value of the actual function call to the command argument of the Button.

Instead what you need to to is to make sure you are assigning an actual function (or in general, any callable object) to the command argument. This makes sure it will be lazily evaluated and only invoked at the time you're actually clicking on the button.

A simple way to do this is by wrapping it in a small lambda function like this:

C_Button = Button(GUI,image=C_Im,command = lambda: get_data('c_name'))
Irmen de Jong
  • 2,739
  • 1
  • 14
  • 26