如何在tkinter中心对齐一个粘性框架内的小部件

12

我正在使用 tkinter 编写 Python3 游戏,但是我在使网格按我的意愿工作方面遇到了一些小问题。我已经查看了至少五页谷歌结果,包括堆栈溢出答案,涵盖我能想到的每种形式来提问这个问题。最后,我不得不创建这个账户来询问这个问题。

我有的:一个位于 frame(topBar)中心的button(newGameButton)和一个label(messageBox),该 frame 本身居中,但水平方向上并未延伸到整个窗口(contentFrame)。

我最好的尝试(通过在 topBar 上放置 sticky=W+E):frame 现在跨越整个窗口,按钮和标签保持相同大小(标签上的 sticky 没有起作用,而按钮上的 sticky 只使其与标签一样宽),并且现在紧贴在 topBar 的左侧。

我想要的效果:使该 frame 跨越整个窗口,同时使标签也跨越整个窗口,并使按钮居中。

topBar 的 columnspan=23 的原因是 content frame 中的其他内容宽度为 23 列(包括第 0 列)。 我将按钮和标签放在一个 frame 中,因为我希望围绕它们的整个框具有边框效果。

代码:

self.contentFrame = Frame(self.root)
self.contentFrame.grid(row=0, column=0)
self.topBar = Frame(self.contentFrame, border=2, relief=RAISED)
self.topBar.grid(row=0, column=0, columnspan=23)
self.newGameButton = Button(self.topBar, text="New Game")
self.newGameButton.grid(row=0, column=0)
self.messageBox = Label(self.topBar, textvariable=self.message, height=2)
self.messageBox.grid(row=1, column=0, sticky=W+E)

有人有什么想法吗?我现在非常绝望。

2个回答

7
问题在于你的所有列都没有权重。它是决定哪些列(和行)获得额外空间的属性。由于你的所有列都没有非零权重,因此没有额外的空间分配给它们,所以它们保持尽可能小。
作为经验法则,你应该始终为框架中的至少一行和一列赋予非零权重。在你的情况下,为所有框架的第0行和第0列赋值1似乎可以解决问题:
self.root.grid_columnconfigure(0, weight=1)
self.root.grid_rowconfigure(0, weight=1)
self.contentFrame.grid_columnconfigure(0, weight=1)
self.contentFrame.grid_rowconfigure(0, weight=1)
self.topBar.grid_columnconfigure(0, weight=1)
self.topBar.grid_rowconfigure(0, weight=1)

有没有一种方法可以在一行中为多个行或列设置权重?或将框架中的所有行和列设置为相同的权重? - Flaming_Dorito

1
通过使用谷歌搜索“如何使tkinter网格自动扩展”,我遇到了这个问题。
引用Bryan Oakley的话:
行和列具有“权重”,描述它们如何增长或缩小以填充主框架中的额外空间。默认情况下,行或列的权重为零,这意味着您已告诉标签填充该列,但您尚未告诉该列填充主框架。
要解决此问题,请给该列分配权重。
class Test():
    def __init__(self,root):
        self.root = root
        self.root.columnconfigure(0, weight=1)
        self.root.config(bg='green')
        self.message = 'test message'

        self.contentFrame = Frame(self.root)
        self.contentFrame.config(background='black',borderwidth=5,relief ='sunken')
        self.contentFrame.grid(row=0, column=0, sticky='news')
        self.contentFrame.columnconfigure(0, weight=1)

        self.topBar = Frame(self.contentFrame, border=2, relief=RAISED)
        self.topBar.grid(row=0, column=0, columnspan=23,sticky=W+E)
        self.topBar.config(background='blue')
        self.topBar.columnconfigure(0, weight=1)

        self.newGameButton = Button(self.topBar, text="New Game")
        self.newGameButton.grid(row=0, column=0)
        self.newGameButton.config(background='red')

        self.messageBox = Label(self.topBar, text=self.message, height=2)
        self.messageBox.grid(row=1, column=0, columnspan=1,sticky=W+E)
        self.messageBox.config(background='yellow')

Test(root)

W+E和与contentFrame相同的columnspan使居中工作。 - MsLate

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接