如何使用grid()水平居中小部件?

L4u*_*dry 8 python tkinter widget grid-layout

grid()用来将小部件放在tkinter窗口中.我试图在窗口的水平中心放置一个标签,让它保持在那里,即使窗口调整大小.我怎么能这样做?

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

Bry*_*ley 13

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

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

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

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()
Run Code Online (Sandbox Code Playgroud)

通过为除了带标签的行和列之外的所有行和列赋予权重,可以获得类似的效果.

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()
Run Code Online (Sandbox Code Playgroud)

  • 只需给标签显示的行和列的权重设置为1,并确保不指定粘性属性即可。默认情况下,行和列的权重设置为零,这意味着两者都不会增长来填充小部件中的任何额外空间。将其设置为1表示它将填充该空间,并随着用户对窗口的扩展而线性增长。正如Bryan提到的,这是使用网格时需要的额外步骤,而使用pack时则不需要。 (2认同)

sco*_*785 5

没有什么特别需要的。小部件将自动位于其父部件的中间。需要告诉家长填满所有可用空间。

from tkinter import *
root = Tk()
root.geometry("500x500+0+0")
frmMain = Frame(root,bg="blue")

startbutton = Button(frmMain, text="Start",height=1,width=4)
startbutton.grid()

#Configure the row/col of our frame and root window to be resizable and fill all available space
frmMain.grid(row=0, column=0, sticky="NESW")
frmMain.grid_rowconfigure(0, weight=1)
frmMain.grid_columnconfigure(0, weight=1)
root.grid_rowconfigure(0, weight=1)
root.grid_columnconfigure(0, weight=1)

root.mainloop()
Run Code Online (Sandbox Code Playgroud)

它使用网格而不是包来放置小部件,并且网格被配置为填充窗口的整个大小。无论窗口大小如何,该按钮都会出现在中心。