Skip to main content
 首页 » 编程设计

python之Tkinter 窗口改变大小因为列表框中的项目

2024年10月25日10mate10pro

您好!

我正在为我制作的简单 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!”中。每次用户点击按钮:http://i.imgur.com/FuTtrOl.png

但是,当项目数量超过列表容量时,它只会变大:http://i.imgur.com/f9atci5.png

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

我想做的是:窗口会一直保持原来的大小,如果item太多或者item长度太长,会有2个滚动条。

我尝试只添加滚动条,但没有帮助。 我还尝试使用 root.resizable(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()