Tkinter and centering

Chad Netzer chad at vision.arc.nasa.gov
Wed Apr 7 18:27:28 EDT 1999


Alexander Schliep wrote:

> Chad Netzer <chad at vision.arc.nasa.gov> writes:
>
> > Well, I don't know if you can ever get the window width and height without
> > first mapping it (displaying).  One option is to open it completely off the
>
> I found a solution in Effective Tcl/Tk. You have to call update_idletasks()
> which forces geometry calculations first and then you can move the window.

Cool, this works!  Although, my quick testing seems to show that the after_idle()
callback combined w/ update_idletasks() is required for it to work.  Also, the
winfo_reqwidth() call must be used instead of winfo_width().  This will help me
with the scrolling frame widget I have devised (like the Pmw widget, but automatically
packs to the correct size, rather than using a specific size.

Anyway, thanks for the tip.  Here is my version of the original poster's demo, fixed
to work like he requested:


from Tkinter import *

def CenterOnScreen():
    root.update_idletasks()
    sw = root.winfo_screenwidth()
    sh = root.winfo_screenheight()
    w = root.winfo_reqwidth()
    h = root.winfo_reqheight()
    newGeometry='+%d+%d' % ((sw/2)-(w/2), (sh/2)-(h/2))
    root.geometry(newGeometry=newGeometry)

root = Tk()
Label(root,text="Cough Cough Cough").pack()
root.after_idle(CenterOnScreen)
root.update()
root.mainloop()


Chad Netzer
chad at vision.arc.nasa.gov






More information about the Python-list mailing list