如何使用 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()
相关文章