Search code examples
tkintertkinter-canvastkinter-buttontkinter-scrolledtext

How to create a scrollable list of buttons in Tkinter?


The code I have now will only print the buttons, it will not create a scroll bar. I want it to print the buttons and allow me to scroll through them. The best I could do is create the scroll bar, but not get it to attach to anything? I'm new to python GUI's so I'm not too familiar with this stuff. This is my code:

def remove1():
        newWindow1 = tk.Toplevel(root)
        newWindow1.title("Remove Suppliers")
        newWindow1.canvas = tk.Canvas()
        newWindow1.canvas.pack()
        sb = tk.Scrollbar(newWindow1.canvas)
        sb.pack()
        newWindow1.canvas.config(yscrollcommand=sb.set)
        sb.config(command = newWindow1.canvas.yview)
        newWindow1.canvas.configure(scrollregion=newWindow1.canvas.bbox("all"))
        newWindow1.canvas.button = []
        i = 0
        for keys in supplier_dict:
            newWindow1.canvas.button.append(tk.Button(newWindow1, text=keys,command = lambda i=i: self.open_this(i)))
            newWindow1.canvas.button[i].pack(side = "top", fill = "both")
            i+=1
        z = 1

        edit_suppliers(supplier_dict)

Solution

  • Frames cannot scroll. The most common solution is to add the frame to a canvas and then attach the scrollbar to the canvas. However, a simpler solution is to put them in a text widget if your goal is a single column of widgets.

    You need to create the buttons as children of the text widget, use window_create to add each button to the end, and then insert a newline to end the line.

    It looks something like this:

    text = tk.Text(root)
    text.pack(side="left")
    sb = tk.Scrollbar(root, command=text.yview)
    sb.pack(side="right")
    text.configure(yscrollcommand=sb.set)
    ...
    for i in range(10):
        button = tk.Button(text, ...)
        text.window_create("end", window=button)
        text.insert("end", "\n")
    text.configure(state="disabled")