Tkinter and centering

Chad Netzer chad at vision.arc.nasa.gov
Wed Apr 7 16:37:43 EDT 1999


Flbill Blipf wrote:

> Hi,
>
> How do I center a window with Tkinter? If I use this:

[Clipped]

>
>
> The window appears in a semi-random location and then staggers to the
> center.
>
> If I remove root.update(), winfo_width and winfo_height both return 1.

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
screen, then update it to the center, but I think many window managers
won't do this (it might work on Windows, but not in Motif, etc.)

Another option is to open the window as centered as possible, then update
to the more correct position, which may be less disconcerting.  For example:

from Tkinter import *

root = Tk()
Label(root,text="Cough Cough Cough").pack()
sw = root.winfo_screenwidth()
sh = root.winfo_screenheight()
w = 120
h = 30
newGeometry='+%d+%d' % ((sw/2)-(w/2), (sh/2)-(h/2))
root.geometry(newGeometry=newGeometry)
root.update()
w = root.winfo_width()
h = root.winfo_height()
newGeometry='+%d+%d' % ((sw/2)-(w/2), (sh/2)-(h/2))
root.geometry(newGeometry=newGeometry)
root.mainloop()


Here, the initial height of 30 and width of 120, is just a rough estimate, but
is pretty close on my machine.  At least the window comes up near the final
resting place. :)  You could also just leave initialize width and height to 1,
but the movement is a bit jarring.

Hope this helps a bit; I don't know if you'll be able to get exactly what you
want, unless you hard code the window sizes (which can be a mess).  Using
'wm_minsize' option may be a slight help.

Chad Netzer
chad at vision.arc.nasa.gov






More information about the Python-list mailing list