添加标签时列表框调整大小:tkinter

listbox resizes when label added: tkinter

我正在使用 .grid() 制作 GUI,因为它有很多按钮。我将它们放在屏幕顶部的交互式 Frame 中 (frameone),底部有 frametwo,我想根据用户的按钮打印消息按。就上下文而言,这是一款战舰游戏。但是当我制作 frametwo 并在其中放入 listbox 时,列表框会调整大小以适合里面的文本。我不想每次输入更多 label 时都必须调整 window 的大小。这是一个工作示例:

from tkinter import *
import tkinter as tk
window = Tk()
window.title("Window")
window.geometry('150x350')     #I wanted the demonstration to work for you.

def addline():                 #Adding sample text
    Label(listbox, text='this is text').grid(sticky=N+W)

frameone = Frame(window, height=10, width=10)
frameone.grid(sticky=N)        #The top where the button goes...

Label(frameone, bg='yellow', text='This is frameone\n\n\n').grid(row=0, column=0)
                               #The yellow here is where all the buttons go...
addtext = Button(frameone, text = 'Add line:', command=addline)
addtext.grid(column=0,row=1)   #Button to add text...

frametwo = Frame(window, bg='red', height=10, width=10)
frametwo.grid(sticky=W)        

listbox = Listbox(frametwo)
listbox.grid(sticky=W, pady=3, padx=3)         #This is the listbox that is wrongly resizing.

scrolltwo = Scrollbar(window, orient=HORIZONTAL)
scrolltwo.configure(command=listbox.yview)
scrolltwo.grid(sticky=S+E)     #I got lazy, I will put this on the side w/rowspan etc.

window.mainloop()

如果这是一个重复的问题或以某种方式非常明显,我深表歉意。另外,抱歉,我的 GUI 太丑了……我不明白为什么这种方法不起作用。在寻找解决方案时,我发现的只是对 .grid 的一些非常好的解释,以及如何使列表在不调整大小时调整大小。一切都有帮助,谢谢。

您将 Listboxlistbox 视为 Frame,但实际上它们的工作方式不同。要将项目添加到 Listbox,请使用它的 insert 函数。因此,要解决您的问题,请替换:

Label(listbox, text='this is text').grid(sticky=N+W)

有:

listbox.insert(END, 'this is text')

有关 tkinter Listbox 小部件的更多信息,请参阅 effbot 文档,here