[Tutor] Why does this function execute before being called?
Alan Gauld
alan.gauld at btinternet.com
Sat Nov 7 04:18:30 EST 2015
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))
> 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.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list