Home > Software design >  Tkinter Scrollbar Does not work for objects inside canvas
Tkinter Scrollbar Does not work for objects inside canvas

Time:10-20

I've made a canvas with two scrollbar and two buttons. But the scrollbar doesn't interact with the buttons inside the canvas. What I want to make, is whenever I scrolls (for example, scroll down), all buttons in the canvas moves to the opposite direction (in this case, move up), but currently they won't move at all.

ws = Tk()
ws.title('PythonGuides')

frame = Frame(
    ws,
    width=500,
    height=400
)
frame.pack(expand=True, fill=BOTH)

canvas = Canvas(
    frame,
    bg='#4A7A8C',
    width=500,
    height=400,
    scrollregion=(0, 0, 700, 700)
)

vertibar = Scrollbar(
    frame,
    orient=VERTICAL
)
vertibar.pack(side=RIGHT, fill=Y)
vertibar.config(command=canvas.yview)

horibar = Scrollbar(
    frame,
    orient=HORIZONTAL
)
horibar.pack(side=BOTTOM, fill=X)
horibar.config(command=canvas.xview)

canvas.config(width=500, height=400)

canvas.config(
    xscrollcommand=horibar.set,
    yscrollcommand=vertibar.set
)

example=tkinter.Button(canvas, text="1")
example.grid(row=3, column=5)

example2 = tkinter.Button(canvas, text="2")
example2.grid(row=6, column=7)

canvas.pack(expand=True, side=LEFT, fill=BOTH)

ws.mainloop()

CodePudding user response:

You cannot scroll items of canvas if they are put into the canvas using .grid()/.pack()/.place().

Use .create_window() instead:

...
example = tkinter.Button(canvas, text="1")
canvas.create_window(10, 10, window=example, anchor="nw")

example2 = tkinter.Button(canvas, text="2")
canvas.create_window(50, 50, window=example2, anchor="nw")
...
  • Related