Tkinter question

dsavitsk dsavitsk at e-coli.net
Mon Oct 21 01:42:58 EDT 2002


Every now and again I get it in my head that some new project would be best
done in Tkinter.  Every time I find myself struggling horribly.  I have the
Grayson book, I have a Fredrik Lundh pdf book from '99.  Somewhere,
something doesn't click. So, along with the specific questions, I am also
looking for a Tkinter moment of clarity.

Currently, I am trying to put together a project with a base window, and one
dialog.  The base window is for most work, but the dialog pops up for
certain editing of parameters, etc. The parts which I am having trouble with
are (a) making the dialog modal (only one can exist, and the root window
can't be reached until the dialog is closed), and (b) I would like to return
data from the dialog to the root window.  Neither of these seem like they
should be terribly difficult, yet they elude me.  Here is a simple sample:

from Tkinter import *
class DialogInterface:
    def __init__(self, parent):
        top = self.top = Toplevel(parent)
        Label(top, text="Value").pack()
        self.e = Entry(top)
        self.e.pack(padx=5)
        b = Button(top, text="OK", command=self.ok)
        b.pack(pady=5)
    def ok(self):
        self.top.destroy()
class RootInterface:
    def __init__(self):
        self.root = root = Tk()
        f = Frame(self.root, width=500, height=150)
        ftop = Frame(f, relief=GROOVE, borderwidth=2)
        self.txtEdit = Entry(ftop)
        self.txtEdit.grid(row=0, column=0, pady=5, sticky=W)
        self.cmdOpen = Button(ftop,
                              width=15,
                              text='Open Dialog',
                              borderwidth=3,
                              relief=GROOVE,
                              command=self._OpenDialog)
        self.cmdOpen.grid(row=1, column=0, pady=5, sticky=W)
        ftop.pack(side=BOTTOM, anchor=S, fill=X)
        f.pack(expand=YES, fill=BOTH)

    def _OpenDialog(self):
        d = DialogInterface(self.root)
        self.root.wait_window(d.top)

if __name__ == '__main__':
    x = RootInterface()
    mainloop()

So the questions are, how do I make the second window modal, and how do I
place the value from DialogInterface.e into RootInterface.txtEdit (as a side
issue, in the above example, when the dialog opens, it does not have focus.
a way to give it focus would be an added bonus).

Thanks for any enlightenment.

-doug





More information about the Python-list mailing list