質問

I'm writing a module where I want to support popup dialogs to indicate errors, but I don't need or want a root window (because I want the module to be independent of the main GUI and share-able between multiple calling applications). I tried simply doing this:

import tkMessageBox
[...stuff...]
if (errorCondition): tkMessageBox.showwarning("My Module","That won't work!")

...but when I run it, a root window appears alongside the message box. I know about the withdraw() method, but since I never imported Tkinter itself and never instantiated Tkinter.Tk(), there's no object for me to use withdraw() on.

An alternative that works is to go ahead and import Tkinter anyway, so I can create the root window myself and then withdraw() it:

import Tkinter
import tkMessageBox
root = Tkinter.Tk()
root.withdraw()
[...stuff...]
if (errorCondition): tkMessageBox.showwarning("My Module","That won't work!")

...but even though that works, it seems klunky to bring in a module and instantiate an object just so I can get rid of it. Plus I don't want to confuse things between this root, and the "real" root in the calling applications.

Going back to the first example, it's obvious that tkMessageBox is doing something under the hood to create the root window on its own. Is there any way I can grab a reference to that root window so I can withdraw() it?

(Environment is Windows 7 and Python 2.7.3.)

役に立ちましたか?

解決

tkMessageBox is built on top of Tkinter, so it is impossible to simply get rid of it: All the functions of the module, like tkMessageBox.showwarning, are wrappers of the _show function. This function creates a Message object, with different arguments depending of the type of dialog you use. Message is a subclass of Dialog, which in turn is a subclass of Toplevel.

Toplevel is a Tkinter widget, so the very first line of this module (apart from the comments) where Dialog is defined is:

from Tkinter import *

Your second solution is the only way to use tkMessageBox correctly, since you are forced to use (at least internally) Tkinter with it.

References:

他のヒント

Note: tkMessageBox does not use tkSimpleDialog, it uses tkCommonDialog. The code of tkCommonDialog is here

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top