首页 > 解决方案 > 添加标签时列表框调整大小:tkinter

问题描述

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

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以及如何在列表没有调整大小时调整大小。一切都有帮助,谢谢。

标签: tkintertkinter-layout

解决方案


您正在将Listbox,listbox视为 a Frame,而实际上它的工作方式不同。要将项目添加到 a Listbox,请使用它的insert功能。因此,要解决您的问题,请替换:

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

和:

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

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


推荐阅读