1

I want to delay a function call. (Or in my mind: python is executing the function in the wrong order). In the below example i could write instead of bf(arg) the two functions bf1 and bf2 and it does work as expected: The function is called whenever the button is pressed. But if i include the arguments in the function the function call is executed only once. Returning the function itself doesn't change the behaviour.

Can you please take a look at it and give me a hint where my logic or understanding of python is wrong.

from tkinter import *
def bf(str):
    print(str)
    # return print(str)  #alternative(same behaviour)

main=Tk(screenName='screen',baseName='base')
button1=Button(master=main,text='b1',command=bf("b1"))
button2=Button(master=main,text='b2',command=bf("b2")) # runs once (and runs here)
button1.pack()
button2.pack()
mainloop()
print('end')

--google and stackoverflow search only return things like delay function call for 1 a specific time interval This is not what i am searching for. :-(

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
soflw
  • 29
  • 3

2 Answers2

8

The issue is that you are calling the function when you create the buttons, instead of passing a callable that TK will call when the button is clicked. Normally you would just pass the function itself:

button1=Button(master=main, text='b1', command=bf)

but since you want to pass arguments to bf you will need to wrap it in a lambda:

button1=Button(master=main, text='b1', command=lambda: bf('b1'))
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
2

What you do in that line is that you don't pass the function but execute it:

button1=Button(master=main,text='b1',command=bf("b1"))

You could either include only the function name, but then you can't pass a parameter to the function:

button1=Button(master=main,text='b1',command=bf)

or you could make use of lambda:

button1=Button(master=main,text='b1',command=lambda:bf("B1"))
elzell
  • 2,228
  • 1
  • 16
  • 26