Tk Dialog Boxes
Eric Brunel
eric.brunel at pragmadev.com
Tue Dec 3 04:35:11 EST 2002
Newt wrote:
> Hi,
>
> I'm trying to build a class to represent a dialog box.
>
> I've got an __init__ method that sets most of the class up, and a
> do_widgets method that defines all the widgets. The last few lines of the
> __init__ metod are
>
> self.wstats.grab_set()
> self.wstats.focus_set()
> self.wstats.wait_window()
>
> which ensures that the screen is responded to before the program continues
> any further.
>
> I've got a couple of buttons on the dialog box which have the following
> code attatched to them:
>
> def bquit(self):
> self.wstats.destroy()
> return
>
> The problem I have is that I want to return a value back to the calling
> program.
>
> I thought about creating a new method which could do all the display and
> the last few lines of the __init__method, but couldn't see how that would
> help. Does the destroy() (as seen above) actually destroy the object, or
> could I set a propery on it to indicate how the form was exited?
The "destroy" method actually destroys the object, but in Tk, not in
Python. So the following code works:
=====================================================================
from Tkinter import *
class MyDialog(Toplevel):
def __init__(self):
Toplevel.__init__(self)
self.__result = None
self.__v = StringVar()
Entry(self, textvariable=self.__v).pack(side=TOP)
Button(self, command=self.validate, text=' OK ').pack(side=TOP)
def validate(self):
self.__result = self.__v.get()
self.destroy()
def get_result(self):
return self.__result
root = Tk()
def runDialog():
dlg = MyDialog()
dlg.transient(root)
dlg.grab_set()
dlg.focus_set()
root.wait_window(dlg)
print dlg.get_result()
Button(root, text='Run dialog', command=runDialog).pack(side=TOP)
Button(text='Quit', command=root.quit).pack(side=TOP)
root.mainloop()
=====================================================================
The only thing you have to be careful about in the method you call when the
dialog is closed ("validate" in the code above) is to do all the Tk stuff
before calling the "destroy" method. In the example above, I don't think it
really matters, but since the "destroy" method destroys the Tk widget and
all its contents, some things may not work if you call it before getting
the info you want to return.
Also note the call to the "transient" method that will prevent the root
window to go over the dialog when it's active.
HTH
--
- Eric Brunel <eric.brunel at pragmadev.com> -
PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com
More information about the Python-list
mailing list