【问题标题】:python tkinter hide the window during widget creationpython tkinter 在小部件创建期间隐藏窗口
【发布时间】:2013-04-23 19:30:19
【问题描述】:

我有一个烦人的小问题,所以我来找你看看你能不能帮忙解决它。 我在 Python2.7 中有以下代码:

# main window
root = tk.Tk()
root.title('My application')
# create the objects in the main window
w = buildWidgetClass(root)
# size of the screen (monitor resolution)
screenWi = root.winfo_screenwidth()
screenHe = root.winfo_screenheight()
# now that widgets are created, find the widht and the height
root.update()
guiWi = root.winfo_width()
guiHe = root.winfo_height()
# position of the window
x = screenWi / 2 - guiWi / 2
y = screenHe / 2 - guiHe / 2
root.geometry("%dx%d+%d+%d" % (guiWi, guiHe, x, y))

所以我创建了主窗口(没有任何大小)我在里面插入小部件,然后我定义结果的大小,并将它放在屏幕中间。

窗口中的小部件数量可能会有所不同,因此生成的大小!

到目前为止,一切都很好,它有效!我唯一的问题是窗口首先出现在屏幕的左上角,然后重新定位到中心。没什么大不了的,但也不是很专业。

所以我的想法是在小部件创建期间隐藏主窗口,然后在定义几何图形后使其出现。

所以在第一行之后,我添加了:

root.withdraw()

然后在最后:

root.update()
root.deiconify()

但是当窗口重新出现时,它没有被小部件重新调整大小并且大小为 1x1 ! 我尝试将 root.withdraw() 替换为 root.iconify(),窗口的大小已正确调整,但令人惊讶的是,最后并未取消图标化!! !

我对此有点迷茫......

【问题讨论】:

  • 您使用什么几何管理器buildWidgetClass?网格还是包?
  • 网格!为什么它很重要?
  • 不是很重要,但是place 不会改变窗口的大小,而packgrid 会。
  • 我明白为什么我的窗口是 1x1 并带有“撤回”。当处于“退出”状态时,窗口管理器会忽略窗口,因此不会更新!因此,即使使用“root.update”,它的大小也是 1x1,然后我用这个值定义几何图形,并且在...之后不会调整大小:-(
  • 我试图在root.update() 之前添加root.deiconify() 并找到窗口的大小并且它可以工作......但我回到开头,窗口出现在顶角然后在中心移动。一定要通过ssh试试看是不是真的像我想象的那么丑……

标签: python tkinter


【解决方案1】:

使用root.winfo_reqwidth 而不是root.winfo_width 可能对您的情况有所帮助。

【讨论】:

  • 很遗憾没有! root.winfo_reqwidth 当它应该超过 600 时返回 200。正如我所说并在 tk 文档中解释的那样,当根窗口“撤回”时,窗口管理器会忽略它并且永远不会更新它的大小
  • 如果在w = buildWidgetClass(root) 之前插入root.update_idletasks()winfo_width 的返回值是多少?
  • 最后你是对的!在我漫长而痛苦的测试中,我删除了root.update()。这显然是root.winfo_reqwidth 没有返回正确值的原因。
【解决方案2】:

终于有了 kalgasnik 的输入,我有了一个工作代码

# main window
root = tk.Tk()
# hide the main window during time we insert widgets
root.withdraw()

root.title('My application')
# create the objects in the main window with .grid()
w = buildWidgetClass(root)
# size of the screen (monitor resolution)
screenWi = root.winfo_screenwidth()
screenHe = root.winfo_screenheight()
# now that widgets are created, find the width and the height
root.update()
# retrieve the requested size which is different as the current size
guiWi = root.winfo_reqwidth()
guiHe = root.winfo_reqheight()
# position of the window
x = (screenWi - guiWi) / 2
y = (screenHe - guiHe) / 2
root.geometry("%dx%d+%d+%d" % (guiWi, guiHe, x, y))
# restore the window
root.deiconify()

非常感谢你们的时间和帮助

【讨论】:

    猜你喜欢
    • 2018-05-29
    • 2019-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-07
    相关资源
    最近更新 更多