Tkinkter - how can I control where the main widget appears

Pierre Quentel quentel.pierre at wanadoo.fr
Wed Nov 5 02:35:19 EST 2003


--- In python-list at yahoogroups.com, DoubleM <mmoum at w...> wrote:
> Given the following trivial program:
> 
> from Tkinter import *
> 
> root = Tk()
> l = Label(root, text = "Hi There")
> l.pack()
> root.mainloop()
> 
> 
> How can I control where the main window appears on the screen?  
Ideally, I
> would like to center it.
> 
> Thanks for your help,
> Mike
> 

Use widget methods to retrieve information about widget and screen 
size, then use the geometry() method whose syntax is

geometry("%dx%d%+d%+d" % (width, height, xoffset, yoffset))

Someting like :

from Tkinter import *

root = Tk()
l = Label(root, text = "Hi There")
l.pack()
c=Canvas(root, width=400,height=300)
c.pack()

# first update idle tasks to get the good values for reqwidth and 
reqheight
root.update_idletasks()

# dimensions of root
width=root.winfo_reqwidth()
height=root.winfo_reqheight()

# dimensions of screen
screenwidth=root.winfo_screenwidth()
screenheight=root.winfo_screenheight()

# position of upper left corner if root is centered
x=(screenwidth-width)/2
y=(screenheight-height)/2

root.geometry("%dx%d%+d%+d" % (width, height, x, y))

root.mainloop()

Hope this helps,
Pierre






More information about the Python-list mailing list