如何将 tkinter 窗口居中并保持“适合儿童"行为? [英] How to center a tkinter window and retain the "fit to children" behavior?

查看:25
本文介绍了如何将 tkinter 窗口居中并保持“适合儿童"行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个内容发生变化的窗口.有时内容比窗口大,所以窗口会扩展以适应它的孩子.但是,当我使用几何"调用将窗口居中时,窗口不再调整大小.您将在下面找到说明这一点的代码.

I have a window whose content changes. Sometimes the content is larger than the window, so the window expands to fit it's children. However, when I center a window using a call to "geometry", the window no longer resizes. Below, you will find code that illustrates this.

如果您注释掉延迟的 center() 函数调用,您会注意到窗口会扩展以适应其内容.如果保持原样,窗口会居中,但不再扩展以适应其内容.

If you comment out the delayed center() function call, you'll notice that the window expands to fit its content. If you leave it as is, the window centers, but no longer expands to fit its content.

是否可以将窗口居中让它继续调整大小以适应其内容?

Is it possible to center a window AND have it continue to resize to fit its content?

from Tkinter import *
import ttk

def center(root):
    w = root.winfo_screenwidth()
    h = root.winfo_screenheight()
    rootsize = tuple(int(_) for _ in root.geometry().split('+')[0].split('x'))
    x = w/2 - rootsize[0]/2
    y = h/2 - rootsize[1]/2
    root.geometry("%dx%d+%d+%d" % (rootsize + (x, y)))

root = Tk()
var = StringVar()
var.set('Small Text')

label = ttk.Label(root, textvariable=var)
label.grid(column=0, row=0)

# Change the text label in a couple of seconds.
def changeit():
    var.set('BIG TXT - ' * 5)
root.after(2000, changeit)

# Comment out this center call and the label expands.
root.after(100, lambda: center(root))
root.mainloop()

推荐答案

当你调用几何命令时,不要提供宽度和高度——只提供 x/y 值.当你给它一个明确的宽度和高度时,你告诉 Tk 我希望窗口正好是这个大小",所以它会关闭它的自动调整大小行为.

When you call the geometry command, don't provide a width and height -- just supply the x/y values. When you give it an explicit width and height, you're telling Tk "I want the window to be exactly this size" so it turns it's auto-resize behavior off.

root.geometry("+%d+%d" % (rootsize + (x, y)))

此外,您可以使用 winfo_width()winfo_height() 来获取窗口的实际大小,而不是解析 geometry<的输出/code> 方法.

Also, you can use winfo_width() and winfo_height() to get the actual size of the window, instead of parsing the output of the geometry method.

这篇关于如何将 tkinter 窗口居中并保持“适合儿童"行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆