如何将 tkinter 窗口居中并保持“适合儿童"行为?

编程入门 行业动态 更新时间:2024-10-23 05:44:06
本文介绍了如何将 tkinter 窗口居中并保持“适合儿童"行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

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

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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-30 08:12:55,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何将   窗口   适合   儿童   quot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!