如何将tkinter小部件置于粘性框架中心

时间:2014-11-13 05:35:42

标签: python button tkinter grid centering

我正在使用 tkinter 在python3中编写游戏,我在让网格做我想做的事情时遇到了一些麻烦。我已经查看了至少五页谷歌搜索结果,包括堆栈溢出答案,以便我可以想到如何提出这个问题。我终于放弃并创建了这个帐户来询问这个问题。

我得到了:按钮(newGameButton)和标签(messageBox),中心位于框架(topBar)它本身居中但不横向覆盖整个窗口(contentFrame)。

我设法获得的最好成绩(通过将sticky=W+E放在topBar上):框架现在跨越整个窗口,按钮和标签保持相同的大小(标签上的粘性没有做到)一个东西,按钮上的粘性只使它像标签一样宽,并且现在卡在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)

有没有人有任何想法?我现在非常绝望。

2 个答案:

答案 0 :(得分:4)

问题是你的列没有任何重量。权重属性决定哪些列(和行)获得任何额外空间。由于没有任何列具有非零权重,因此没有任何额外空间分配给它们,因此它们保持尽可能小。

根据经验,您应该始终在一个帧中至少给出一行和一列非零权重。在您的情况下,给第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)

答案 1 :(得分:0)

使用'如何使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)