Tkinter: Relative positioning of Toplevels

Julie Torborg jtorborg at fnal.gov
Mon Jul 22 16:24:14 EDT 2002


Hello.

I was wondering if anyone can tell me how to position a toplevel
relative to another widget.

Basically, I want to end up with something that behaves like a
pull-down menu, except that you can't select anything--it just
displays information. I'm not clever enough to hack the OptionMenu
class, so I've been trying to use a button/toplevel combination.  I
want the toplevel to appear "anchored" to the button.  The problem is,
I can't get the toplevel to show up anywhere near the button. I use

self.x=nb.winfo_geometry()

to get the position of the button relative to it's parent, but when I
do:

self.tl.geometry(self.x)

it draws the toplevel with these coordinates relative to the screen.
I'm trying to write this as a class that doesn't care what frame it's
embedded in, so it's impractical for me to try to recursively locate
all the upstream windows.

My code is below.  Thanks for any advice.

Julie

class eachModule:
    def __init__(self, pf):
        self.pf=pf       
        nb=Button(self.pf, text="Popup")
        nb.bind("<ButtonPress-1>", self.pr)
        nb.bind("<ButtonRelease-1>", self.rel)
        nb.pack()
        self.pf.update_idletasks()
        self.x=nb.winfo_geometry()
    
    def pr(self, event):
        self.tl=Toplevel(self.pf)
        self.tl.overrideredirect(1)
        self.tl.geometry(self.x)
        label=Label(self.tl, text="info up")
        label.pack()

    def rel(self, event):
        self.tl.destroy()


if __name__=="__main__":

    def die():
        root.quit()
        root.destroy()
        
    root=Tk()

    em=eachModule(root)
    
    eb=Button(root, text="Exit", command=die) 
    eb.pack()
    root.mainloop()



More information about the Python-list mailing list