3

我正在使用 Tkinter 和 python 创建一个非常简单的 UI,但是我在调​​整 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()
4

1 回答 1

2

在我看来,使用包几何管理器可以更轻松地进行布局。问题之一是您试图使用rowspancolumspan选项使每个小部件的宽度和高度适合其位置。此外,由于canvas是在一个框架内,你必须认为它就像在一个新窗口内,所以一个简单的调用canvas.grid()就足够了。

但是,pack()您只需将textbox,run_buttonclear_button放在一个新框架内:

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()
于 2013-04-02T20:47:06.397 回答