我一直在使用Tkinter和Python 2.7将菜单放在一起。它在功能上有效,但布局非常混乱。我使用.grid()方法来组织小部件,但它们互相干扰,所以我的列表框小部件比按钮高,所以它们间隔开等等。我该怎么做才能解决这个问题? 我得到的结果如下所示:
我想要实现的目标是:
这是我的代码:
import Tkinter as tk
root = tk.Tk()
root.title("Test")
command = []
class button():
def __init__(self, root, text_in, x, y, command):
self.text = text_in
self.pressed = False
self.button = tk.Button(root, text=text_in, width = 15, height = 5, command = lambda: add_to_command(self.text))
self.button.grid(row=x, column = y)
def add_to_command(word):
command.append(word)
command.append(' ')
def print_command(command, command_line):
if command_line.get():
command = command_line.get()
else:
command = ''.join(command)
print command
button1 = button(root, "1", 0, 1, command)
button2 = button(root, "2", 0, 2, command)
button3 = button(root, "3", 1, 1, command)
button4 = button(root, "4", 1, 2, command)
button5 = button(root, "5", 2, 1, command)
button6 = button(root, "6", 2, 2, command)
button7 = button(root, "7", 3, 1, command)
button8 = button(root, "8", 3, 2, command)
command_line = tk.Entry(root, width = 100, takefocus=1)
command_line.grid(row = 0,column = 3, padx = 10)
go_button = tk.Button(root, text="Enter", width = 15, height = 5, command = lambda: print_command(command, command_line))
go_button.grid(row=0, column=5)
list_box = tk.Listbox(root)
list_box.grid(row = 1, column = 3)
list_box.insert(0, "ENTRY 1")
list_box.insert(1, "ENTRY 2")
root.mainloop()
答案 0 :(得分:2)
你可以告诉网格允许(强制)一个小部件占用多行/列,columnspan
参数为grid()
,即:
...
list_box.grid(row=1, column=3, rowspan=3)
...
这会告诉您的list_box
覆盖(最多)三行(如果空间比小部件多,则可能需要anchor
它到(N)正+ (S)outh延伸可用空间)columnspan
以相同的方式工作。
作为一个注释,从左上角跨越锚;每个row=1, column=3
和rowspan
为columnspan
的{{1}}将占用第1-3行和第3-5列。