繁体   English   中英

如何在粘性框架中将Tkinter小部件居中

[英]How to center a tkinter widget in a sticky frame

我正在使用tkinter在python3中编写游戏,但是让网格做我想做的事情有点麻烦。 我已经浏览了至少五页的google结果,包括有关如何提出这个问题的各种变体的堆栈溢出答案。 我终于放弃了,创建了这个帐户来询问这个问题。

我得到的是:一个按钮 (newGameButton)和一个标签 (messageBox)在框架 (topBar)中居中,该框架本身居中,但没有水平地跨整个窗口(contentFrame)。

我设法获得的最好的效果(通过在topBar上放置sticky=W+E ):框架现在跨整个窗口,按钮和标签保持相同的大小(标签上的粘滞不起作用,标签上的粘滞不起作用)按钮仅使其宽度达到标签的宽度),并且现在贴在topBar的左侧。

我想要做的是:使框架跨整个窗口,标签也跨整个窗口,并且按钮居中。

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

码:

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)

有人知道吗? 在这一点上我非常绝望。

问题在于您的所有列都没有权重。 权重属性决定了哪些列(和行)获得任何额外的空间。 由于没有一个列的权重为非零,因此没有多余的空间分配给它们,因此它们将保持尽可能的小。

根据经验,一帧中的至少一行和一列始终应赋予非零权重。 在您的情况下,将所有帧的行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)

通过在Google中使用“如何使tkinter网格扩展”,我遇到了问题。

布莱恩·奥克利(Bryan Oakley)的名言

行和列具有“权重”,该权重描述它们如何增大或缩小以填充母版中的多余空间。 默认情况下,行或列的权重为零,这意味着您已经告诉> label填充了该列,但没有告诉该列填充了主框架。

要解决此问题,请为列指定权重。

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM