我正在尝试使用Tkinter模块(Python 2.7)中的功能来创建一个GUI,其中有8个小部件放在7行×5列网格上(抱歉我没有包含图像;对话框是不允许我浏览和上传保存的图片。)
(Widget,start_row,start_col,row_span,column_span):
然而,当我运行我的代码时,按钮和Frame3被渲染得很好,但是Frame1垂直“压缩”了Frame2。任何建议将不胜感激。 (我已阅读建议的StackOverflow答案,似乎没有提供可用于解决我的问题的信息。此外,我在网上广泛搜索无济于事。)
from Tkinter import *
class Application(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.master.title("Grid Manager")
self.master.rowconfigure(0, weight=1)
self.master.columnconfigure(0, weight=1)
for i in range(5):
self.master.button = Button(master, text = "Button {0}".format(i))
self.master.button.grid(row=6, column=i, sticky=W+E)
self.Frame1 = Frame(master, bg="red")
self.Frame1.grid(row = 0, column = 0, rowspan = 3, columnspan = 2, sticky = W+E+N+S)
self.Frame2 = Frame(master, bg="blue")
self.Frame2.grid(row = 2, column = 0, rowspan = 3, columnspan = 2, sticky = W+E+N+S)
self.Frame3 = Frame(master, bg="green")
self.Frame3.grid(row = 0, column = 2, rowspan = 6, columnspan = 3, sticky = W+E+N+S)
root = Tk()
app = Application(master=root)
app.mainloop()
更新:现在我在我的个人电脑上,这里分别是我想要的结果和我得到的结果的图像:
答案 0 :(得分:14)
在使用我的代码几个小时后,我终于能够创建我想要的GUI。关键是循环遍历行和列,并分别使用rowconfigure和columnconfigure设置其权重。代码如下:
from tkinter import *
class Application(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.grid()
self.master.title("Grid Manager")
for r in range(6):
self.master.rowconfigure(r, weight=1)
for c in range(5):
self.master.columnconfigure(c, weight=1)
Button(master, text="Button {0}".format(c)).grid(row=6,column=c,sticky=E+W)
Frame1 = Frame(master, bg="red")
Frame1.grid(row = 0, column = 0, rowspan = 3, columnspan = 2, sticky = W+E+N+S)
Frame2 = Frame(master, bg="blue")
Frame2.grid(row = 3, column = 0, rowspan = 3, columnspan = 2, sticky = W+E+N+S)
Frame3 = Frame(master, bg="green")
Frame3.grid(row = 0, column = 2, rowspan = 6, columnspan = 3, sticky = W+E+N+S)
root = Tk()
root.geometry("400x200+200+200")
app = Application(master=root)
app.mainloop()
答案 1 :(得分:4)
由于第1,2和3帧内部没有任何小部件,并且您没有给它们任何高度,因此它们的自然尺寸将是一个像素高。如果你在frame2中放置一些东西,或者给frame2一个高度,它就会显示出来。
答案 2 :(得分:1)
如果您喜欢尝试pytkgen(https://github.com/tmetsch/pytkgen或http://pypi.python.org/pypi/pytkgen/) - 它会从JSON文件生成Tkinter GUI并负责权重,高度和行/列配置。请参阅此处的示例:https://github.com/tmetsch/pytkgen/tree/master/examples