Why does the “geometry()” method work with a delay?

元气小坏坏 提交于 2021-02-18 11:13:06

问题


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.


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/8934334/why-does-the-geometry-method-work-with-a-delay

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!