ohad987
ohad987

Reputation: 336

Tkinter window changing size becuase items in listbox

Hello!

Im developing a GUI to simple python script I made (The GUI developed using SpecTcl). The script is searching a website and show the search results in a list box.

The code is:

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) 

To demonstrate the problem, i made a simple program which add to the list "hello world!" every time the user click the button: https://i.sstatic.net/EsA1K.png

but, when there are more items than the list size capacity, its just get bigger: https://i.sstatic.net/8WvG2.png

It also happneds horizontally if the item is too long: i.imgur.com/a88DRxy.png

What I want to do is: the window will always stay in his original size, and there will be 2 scrollbars if there are too many items or the item length is too high.

I tried just adding scrollbars but it didnt help. I also tried forcing the screen size using root.resizable(0,0), and it still got bigger and bigger.

It's my first question here, if i did something wrong/didnt described the problem well just tell me and ill fix :)

Thanks!

Upvotes: 2

Views: 622

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 385890

What you describe is not the default behavior of a tk listbox widget. Here is an example showing a listbox with scrollbars:

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

Upvotes: 2

Related Questions