Python tkinter网格布局问题

3
我正在使用Tkinter和Python创建一个非常简单的用户界面,但我在调整GUI元素大小和使用网格格式将它们正确放置方面遇到了问题。这是我尝试实现的一级近似图:
以下是我目前拥有的代码。我一直在接近,但我不认为我真正理解自己在做什么。非常感谢您的帮助!
#User interface
root = Tk()
window_width = root.winfo_screenwidth()
window_height = root.winfo_screenheight()
root.geometry    ("%dx%d"%(window_width,window_height))

menu_bar = Menu(root)
menu = Menu(menu_bar, tearoff=0)
menu.add_command(label="Open", command = open_file)
menu.add_command(label="Save", command = save)
menu.add_separator()
menu.add_command(label="Quit", command = exit)
menu_bar.add_cascade(label="File",menu=menu)

root.config(menu=menu_bar)

#textbox is the window in which the code is written
textbox = Text(root, width=50, height = window_height/20+4)

#canvas is where the car will go
canvas_frame= Frame(root, width = window_width/1.5, height = window_height-200)
canvas_frame.configure(borderwidth=1.5,background='black')
canvas = Canvas(canvas_frame, width = window_width/1.5, height = window_height-200)

#console to print to
console = Text(root, width = int(window_width/1.5), height = 10)

run_button = Button(root, text = "Run", command = lambda:generate_program(textbox.get(1.0,END)))

clear_button = Button(root, text = "Clear text", command = clear)

#add them to frame
textbox.grid(row=0, column=0, rowspan=20, columnspan=10)
run_button.grid(row=21,column=0)
clear_button.grid(row=21,column=1)
canvas_frame.grid(row=0,rowspan=10,column=21,columnspan=25)
canvas.grid(row=0, rowspan=1, column=21, columnspan=25)
console.grid(row = 1, rowspan=1, column = 21, columnspan=25)

root.mainloop()
1个回答

2
在我看来,使用pack几何管理器可以使布局更加简单。其中一个问题是你试图通过rowspan和columspan选项让每个部件的宽度和高度适应其位置。此外,由于canvas位于frame内部,你必须考虑它就像在一个新窗口内部一样,因此只需简单调用canvas.grid()即可。
然而,使用pack(),你只需要将textbox、run_button和clear_button放置在一个新的frame中:
left_frame = Frame(root)
textbox = Text(left_frame, ...)
run_button = Button(left_frame, ...)
clear_button = Button(left_frame, ...)

canvas_frame= Frame(root, ...)
canvas_frame.configure(borderwidth=1.5,background='black')
canvas = Canvas(canvas_frame, ...)
console = Text(root, ...)

left_frame.pack(side=LEFT)
textbox.pack()
run_button.pack(side=LEFT)
clear_button.pack()
canvas_frame.pack()
canvas.pack()
console.pack()

2
同意 - 明显有一个左侧和右侧。我会从pack开始。然后,每一边都有明显的顶部和底部区域。使用grid布局来处理顶部/底部部分的好处是可以为每个部分指定权重,以可能获得更有效的调整大小行为。此外,拥有左侧和右侧使将来添加带分隔窗口更容易。 - Bryan Oakley

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