Tkinter help - Why this behavior ? (py3)

Alf P. Steinbach alfps at start.no
Sat Jun 5 13:07:43 EDT 2010


* Dodo, on 05.06.2010 15:46:
> Hi,
>
> let's consider this exemple :
>
> from tkinter import *
> from tkinter.ttk import *
>
> class First:
> def __init__(self):
> self.root = Tk()
> B = Button(self.root, command=self.op)
> B.pack()
>
> self.root.mainloop()
>
> def op(self):
> Second(self)
> print("print")
>
>
> class Second:
> def __init__(self, parent):
> root = Toplevel(parent.root)
> root.grab_set()
>
> root.mainloop()
>
>
> First()
>
>
>
> when I close the second window, the print is NOT executed. It's done
> when I close the first window.
> Why do it "freeze" my function?

First, sorry about Thunderbird 3.x messing up the quoting of the code.

Don't know what they did to introduce all those bugs, but anyway, Thunderbird 
3.x is an example that even seasoned programmers introduce an unbelievable 
number of bugs, I think mostly just by repeating code patterns blindly.

In your code above you're doing as the TB programmers presumably did, repeating 
a code pattern that you've seen has worked, without fully grokking it. The call 
to 'mainloop' enters a loop. A button press causes your callback to be invoked 
from within that loop, but your code then enters a new 'mainloop'.

Don't.

Except for modal dialogs the single top level 'mainloop' suffices (all it does 
is to dispatch "messages" to "handlers", such as your button press callback). 
So, just place a single call to 'mainloop' at the end of your program. Remove 
the calls in 'First' and 'Second'.


Cheers & hth.,

- Alf


-- 
blog at <url: http://alfps.wordpress.com>



More information about the Python-list mailing list