Search code examples
tkinterscrollbartkinter-canvas

Scrollbar Tkinter not scrolling


I have a scroll bar on tkinter but it doesn't let me scroll the page, when I scroll it does not move at all. (The scrollbar is there)

def new_window(serial, model, n_comp, ):
newwindow = Toplevel(root)
newwindow.title("Components")

# Canvas
my_canvas = Canvas(newwindow)
my_canvas.pack(side=LEFT, fill=BOTH, expand=1)

# Scrollbar
my_scrollbar = ttk.Scrollbar(newwindow, orient=VERTICAL, command=my_canvas.yview())
my_scrollbar.pack(side=RIGHT, fill=Y)

# Configure the canvas
my_canvas.configure(yscrollcommand=my_scrollbar.set)
my_canvas.bind('<Configure>', lambda e: my_canvas.configure(scrollregion=my_canvas.bbox("all")))

# Create a frame inside the canvas
second_frame = Frame(my_canvas)

# Add that newframe to a window in the canvas
my_canvas.create_window((0, 0), window=second_frame, anchor="nw")

ls = []  # Lista modello + seriali
ls_old_model = []  # Lista modelli già usati
for y in range(0, len(serial)):
    verifica = model[y]
    if verifica in ls_old_model:
        pass  # Se il modello è già stato usato non faccio nulla e passo ai modelli successivi
    else:
        blocco = FALSE  # Blocco per inserire il modello solo una volta. Quando attivo verranno inseriti solo i
        # seriali
        for x in range(0, len(serial)):
            if model[x] == verifica:
                if blocco == FALSE:
                    ls.append(model[x])
                    blocco = True
                    ls.append("  - " + serial[x])
                else:
                    ls.append("  - " + serial[x])
    ls_old_model.append(verifica)
new_ls = "\n\n".join(ls)
text1 = Message(second_frame, text=(f'HARD_FAIL components to be tested for MIL01 = {n_comp} \n\n\n'
                                    f'Component type: \n\n\n'
                                    f'{new_ls}'))
text1.pack()

How can I solve it? I saw similar questions but I couldn't fix it. Thank you all.


Solution

  • The issues is caused by command=my_canvas.yview() in ttk.Scrollbar(...) which execute my_canvas.yview() immediately and assign the result None to command option. So the scrolling does not work.

    It should be command=my_canvas.yview instead.

    Also to update the scrollregion of my_canvas, the <configure> event should be bound on second_frame instead of my_canvas because the scrollregion need to be updated whenever the second_frame is resized, not my_canvas.