2016-07-06 64 views
1

我一直在使用Tkinter和Python 2.7一起放置一个菜单。它在功能上起作用,但布局非常混乱。我使用.grid()方法来组织窗口小部件,但它们互相干扰,所以我的列表框窗口部件比按钮高,所以它们间隔开等。我能做些什么来解决这个问题? 我得到的结果如下所示:Tkinter小部件布局是否错误?

enter image description here

用什么我想在这里实现引出:

enter image description here

这是我的代码:

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)orth +(S)outh伸展可用空间)columnspan以相同的方式工作。

作为一个说明,跨越左上角的锚; row=1, column=3rowspancolumnspan各3将占用行1-3和列3-5。