Monday 14 January 2008

tkinter conflicts with IDLE

The code you are told to write will invoke a Tkinter outer loop with root.mainloop(), and yet IDLE itself has already got an outer loop going. And creating two outer loops can keep you from closing Python (read further for solutions).

1.
To summarize, the bottom line is literally this: When using a root.mainloop() as your program's last command, be ready to "comment it out" (put a # number/pound sign at that line's beginning) when running from IDLE, and to undo the commenting when booting it outside of IDLE, such as from Windows Explorer.

root.mainloop() #ready to boot directly

# root.mainloop() #ready to run under IDLE

2.
A better solution: In examining newer Tkinter programming examples linked to these pages, including the revised tkex1.py above, you will find a usingIDLE Boolean variable that is set instead of commenting out the root.mainloop() command. This is cleaner and also handier, as it gets used in deciding other factors in how to destroy the top window upon closing, including whether or not the WM_DELETE_WINDOW protocol is employed.
Or:
>>> import sys
>>> for eachPath in sys.path:
if eachPath.find("idlelib"):
usingIDLE = 1
print 'find it'

>>> if usingIDLE:
# root.mainloop() # this means don't run the root.mainloop() for tkinter application.



Just to be clear, understand that this issue is in regard to Ctrl-F5/Running a Tkinter script from IDLE. If you boot a script from the OS or Python command line, or from Windows Explorer, then most of the time it doesn't seem to matter whether IDLE is also running.

This overall conflict situation appears to be also true with other Tkinter-based environments, such as the IDE that comes with Mac Python.

3.
Another solution: Don't use root.mainloop() at all, but instead use root.wait_frame(yourToplevelFrame). The first two example scripts on the Tkinter 3D page use this approach, as explained here.

No comments:

My photo
London, United Kingdom
twitter.com/zhengxin

Facebook & Twitter