[Tutor] Why does this function execute before being called?

Chris Roy-Smith chris_roysmith at internode.on.net
Sat Nov 7 04:28:47 EST 2015


On 07/11/15 20:18, Alan Gauld wrote:
> On 07/11/15 04:34, Chris Roy-Smith wrote:
>
>> def genF(ofield): ...
>>      for x in range(10):
>
>> def second():
>>      main=Toplevel(root)
>>      ofield=Text(main, height=15, width=15)
>>      ofield.pack()
>>      B3=Button(main, text='exit', command=main.destroy)
>>      B3.pack()
>>      B4=Button(main, text='fill text', command=genF(ofield))
>
> You call a function by sup[plying the parens after its name.
> So the function gets called here. The normal way to circumvent
> that in Tkinter is to use a lambda expression to defer execution,
> like so:
>
> B4=Button(main, text='fill text', command=lambda wgt=ofield : genF(wgt))

This certainly wasn't obvious from what I could find on the internet. 
Now I see an application for Lambda
>
>>      B4.pack()
>>      main.mainloop()
>
> I'm not sure you need the second mainloop. I think the
> root level mainloop will work for your window too.
>
>
Just tried out leaving this second mainloop, and every works the same. I 
had assumed I needed to create a loop the same as the top window.

Thanks for clearing up this mystery



More information about the Tutor mailing list