python - Tkinter 窗口由于列表框中的项目而改变大小

标签 python listbox tkinter window

你好!

我正在为我制作的简单 python 脚本开发一个 GUI(使用 SpecTcl 开发的 GUI)。 该脚本正在搜索网站并在列表框中显示搜索结果。

代码是:

results = search(query) #return a list of results, or False if there are no results
msg = msgMngr()
if results == False:
    msg.onWarn("No results", "No search results to " + query) #Warn the user that there are no results
else: 
    self.list.delete(0, END) #clear listbox
    for item in results: #enter all items to the listbox
        self.list.insert(END, item) 

为了演示这个问题,我制作了一个简单的程序,将“hello world!”添加到列表中每次用户单击按钮时:/image/EsA1K.png

但是,当项目数量超过列表大小容量时,它就会变得更大:/image/8WvG2.png

如果项目太长,它也会水平发生:i.imgur.com/a88DRxy.png

我想要做的是:窗口将始终保持原来的大小,如果项目太多或项目长度太高,将会有2个滚动条。

我尝试只添加滚动条,但没有帮助。 我还尝试使用 root.resized(0,0) 强制屏幕大小,但它仍然变得越来越大。

这是我的第一个问题,如果我做错了什么/没有很好地描述问题,请告诉我并修复:)

谢谢!

最佳答案

您所描述的不是 tk 列表框小部件的默认行为。下面是一个显示带有滚动条的列表框的示例:

import Tkinter as tk

class Example(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent, borderwidth=1, relief="sunken")
        b = tk.Button(self, text="search", command=self.add_one)

        self.lb = tk.Listbox(self, borderwidth=0)
        self.lb.pack(fill="both", expand=True)
        vsb = tk.Scrollbar(self, orient="vertical", command=self.lb.yview)
        hsb = tk.Scrollbar(self, orient="horizontal", command=self.lb.xview)
        self.lb.configure(yscrollcommand=vsb.set, xscrollcommand=hsb.set)

        b.grid(row=0, column=0, columnspan=2)
        vsb.grid(row=1, column=1, sticky="ns")
        self.lb.grid(row=1, column=0, sticky="nsew")
        hsb.grid(row=2, column=0, sticky="ew")
        self.grid_rowconfigure(1, weight=1)
        self.grid_columnconfigure(0, weight=1)

    def add_one(self):
        self.lb.insert("end", "hello world!")

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(fill="both", expand=True)
    root.mainloop()

关于python - Tkinter 窗口由于列表框中的项目而改变大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26372573/

相关文章:

c++ - PySide 中的多线程 Boost Python C++ 代码

python - 使用Python在云端进行并行处理

python - 如何在 python 中将数据框的邮政编码排序到 cargo 区域?

c# - 以并行方式将项目添加到 ListBox

python-3.x - 下拉菜单更改顺序并每次删除一个选项 - Python

python - 使用 for 循环绘制数据框列

c# - 防止 ScrollViewer 处理 ListBox 项中的 Tap 事件

Python tkinter - 在文本小部件中自动缩进一行

Python tkinter - 成功从顶层继承

python - 无法将图像添加到 Tkinter 列表框