gpt4 book ai didi

python - Tkinter 小部件布局错误?

转载 作者:行者123 更新时间:2023-12-01 03:51:08 26 4
gpt4 key购买 nike

我一直在使用 Tkinter 和 Python 2.7 将菜单放在一起。它可以正常工作,但布局非常困惑。我使用 .grid() 方法来组织小部件,但它们相互干扰,因此我的列表框小部件比按钮高,因此它们间隔开等。我可以做什么来解决这个问题?我得到的结果如下所示:

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()

最佳答案

您可以使用 grid()columnspan 参数告诉网格让(强制)小部件占用多行/列,即:

...
list_box.grid(row=1, column=3, rowspan=3)
...

这将告诉您的 list_box 覆盖(最多)三行(如果空间比小部件更多,您可能需要将其锚定到 (N) orth + (S)outh 以拉伸(stretch)可用空间)columnspan 的工作方式相同。

作为注释,从左上角跨越 anchor ; row=1,column=3,其中 rowspancolumnspan 各为 3,将占用第 1-3 行和第 3-5 列。

关于python - Tkinter 小部件布局错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38233348/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com