简体   繁体   English

Python Tkinter Grid问题-用户错误?

[英]Python Tkinter Grid issue - user error?

I am trying to create a basic layout for a Python gui using Tkinter. 我正在尝试使用Tkinter为Python gui创建基本布局。

#!/usr/bin/env python
from Tkinter import *

#create root
root = Tk()

banner = Frame(root, width=500)
body = Frame(root, width=500)
banner.grid()
body.grid()


bannercontent = Label(banner, bg="Green", text="Green").grid(row=0, column=0)
bannerbuttons = Label(banner, bg="Red", text="Red").grid(row=0, column=1)
bodycontent = Label(body, bg="Blue", text="Blue").grid(row=1, column=0, columnspan=2, sticky=E+W)
root.mainloop()

However with the above, the blue label is not expanding to fill the 2 columns as I'd wish, ie fill the space under Green and Red. 但是,使用上面的方法,蓝色标签没有按照我的意愿扩展为填充两列,即填充绿色和红色下面的空间。 What am I doing wrong please? 请问我做错了什么?

Example here http://imgur.com/nGWQX9y 此处示例http://imgur.com/nGWQX9y

例

Thank you in advance 先感谢您

You have a few things wrong with your code. 您的代码有些错误。 First, you aren't specifying a sticky option, so widgets won't "stick" (ie: grow or shrink) to the edges of the cell. 首先,您没有指定sticky选项,因此小部件不会“粘”(即增大或缩小)到单元格的边缘。 Your bodycontent label is in fact occupying two columns, but the frame itself isn't expanding to the full width of the main window. 实际上,您的bodycontent标签占据了两列,但是框架本身并未扩展到主窗口的整个宽度。

The second problem is that you seem to be assuming that columns span the entire app. 第二个问题是您似乎假设列跨越了整个应用程序。 They do not. 他们不。 You have two columns in banner because you put a widget in column 0 and column 1. However, bodycontent only has one column (or, you could say it has two, but the second column is of zero width). 您在banner有两列,因为您将小部件放在了第0列和第1列中。但是, bodycontent只有一列(或者,您可以说它有两列,但是第二列的宽度为零)。 The column sizes in the first frame have no relationship to the columns in the second frame. 第一帧中的列大小与第二帧中的列无关。 Thus, the bottom frame contents won't line up with the top frame. 因此,底部框架的内容不会与顶部框架对齐。

A third problem that your code has is that you aren't giving your rows or columns "weight". 您的代码的第三个问题是您没有为行或列赋予“权重”。 The weight attribute tells Tkinter how to allocate any extra space. weight属性告诉Tkinter如何分配额外的空间。 Since you haven't done that, your GUI does not resize in a pleasant way when you grow or shrink the window. 由于尚未执行此操作,因此在增大或缩小窗口时,GUI不会以令人愉快的方式调整大小。 A good rule of thumb is that for any given container, at least one row and one column should be given a non-zero weight. 一个好的经验法则是,对于任何给定的容器,至少一行和一列的权重都应为非零。

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

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