8

If i run this Python code:

from Tkinter import *; w = Tk(); w.geometry( "640x480" ); print( w.geometry() )

i will get "1x1+0+0" output. But if i start interpreter and execute this as two separate commands, i will get completely different output:

>>> from Tkinter import *; w = Tk(); w.geometry( "640x480" ) 
'' 
>>> w.geometry() 
'640x480+101+73'

It seems geometry is not applied instantly, something else is needed : (. Maybe anyone knows what i need to do in order to update geometry inplace? I need it to correctly center/position main and child windows.

nbro
  • 15,395
  • 32
  • 113
  • 196
grigoryvp
  • 40,413
  • 64
  • 174
  • 277
  • Good question. I assume there is some delay time between creating the window, and reading its size. Strangely, if I put a print "foo"; in between the last 2 statements it works, but if I put two of them python seems to hang. – jgritty Jan 19 '12 at 22:58

2 Answers2

6

Calling update_idletasks() on a window (or a widget) will force its geometry to update.

Here's a little text snippet from the Tkinter reference:

The geometry is not accurate until the application has updated its idle tasks. In particular, all geometries are initially "1x1+0+0" until the widgets and the geometry manager have negotiated their positions.

D K
  • 5,530
  • 7
  • 31
  • 45
0

This completes, but gives wrong answer:

from Tkinter import *; w = Tk(); w.geometry( "640x480" ); print "foo"; print( w.geometry() )

''
foo
1x1+0+0

This seems to hang:

from Tkinter import *; w = Tk(); w.geometry( "640x480" );  print "foo"; print "foo"; print( w.geometry() )

Only a keyboard interrupt seems to get me out.

Sure enough, this does seem to work properly:

from Tkinter import *; w = Tk(); w.geometry( "640x480" ); w.update_idletasks(); print( w.geometry() )

''
640x480+5+27
jgritty
  • 11,660
  • 3
  • 38
  • 60