如何使用grid()将小部件水平居中? [英] How to horizontally center a widget using grid()?

查看:290
本文介绍了如何使用grid()将小部件水平居中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用grid()将小部件放置在tkinter窗口中.我正在尝试在窗口的水平中心放置一个标签,并将其放置在那里,即使窗口已调整大小.我该怎么做呢?

I am using grid() to place widgets in a tkinter window. I am trying to put a label on the horizontal center of a window and have it stay there, even if the window is resized. How could I go about doing this?

顺便说一句,我不想​​使用pack().我想继续使用grid().

I don't want to use pack(), by the way. I would like to keep using grid().

推荐答案

没有技巧-默认情况下,小部件位于分配给它的区域的中心.只需将标签放在没有任何sticky属性的单元格中,它将居中.

There's no trick -- the widget is centered in the area allocated to it by default. Simply place a label in a cell without any sticky attributes and it will be centered.

现在,另一个问题是,如何获得它分配为居中的区域.这取决于许多其他因素,例如那里还有其他小部件,它们的排列方式等.

Now, the other question is, how to get the area it is allocated to be centered. That depends on many other factors, such as what other widgets are there, how they are arranged, etc.

这是一个显示单个居中标签的简单示例.它通过确保行和列占用所有额外空间来实现此目的.请注意,无论您将窗口多大,标签都将居中.

Here's a simple example showing a single centered label. It does this by making sure the row and column it is in takes up all extra space. Notice that the label stays centered no matter how big you make the window.

import Tkinter as tk

class Example(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)
        label = tk.Label(self, text="This should be centered")
        label.grid(row=1, column=1)
        self.grid_rowconfigure(1, weight=1)
        self.grid_columnconfigure(1, weight=1)

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).grid(sticky="nsew")
    root.grid_rowconfigure(0, weight=1)
    root.grid_columnconfigure(0, weight=1)
    root.mainloop()

通过赋予所有行和列权重 带有标签的权重,您可以得到类似的效果.

You can get a similar effect by giving a weight to all rows and columns except the one with the label.

import Tkinter as tk

class Example(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)
        label = tk.Label(self, text="This should be centered")
        label.grid(row=1, column=1)

        self.grid_rowconfigure(0, weight=1)
        self.grid_rowconfigure(2, weight=1)
        self.grid_columnconfigure(0, weight=1)
        self.grid_columnconfigure(2, weight=1)

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).grid(sticky="nsew")
    root.grid_rowconfigure(0, weight=1)
    root.grid_columnconfigure(0, weight=1)

    root.mainloop()

这篇关于如何使用grid()将小部件水平居中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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