Skip to content
Advertisement

Scroll bars not working correctly with canvas

The scroll bars move the canvas but they always snap back to the top or the left. What am I doing wrong?

import tkinter as Tk
root = Tk.Tk()
root.rowconfigure(0,weight=1)
root.columnconfigure(0,weight=1)
frame = Tk.Frame(root)
frame.grid(row=0, column=0, sticky='NSEW')
frame.rowconfigure(0,weight=1)
frame.columnconfigure(0,weight=1)
canvas = Tk.Canvas(frame)
canvas.grid(row=0, column=0, sticky='NSEW')
scroll_x = Tk.Scrollbar(frame, orient="horizontal", command=canvas.xview)
scroll_x.grid(row=1, column=0, sticky="ew")
scroll_y = Tk.Scrollbar(frame, orient="vertical", command=canvas.yview)
scroll_y.grid(row=0, column=1, sticky="ns")
canvas.create_oval(0,0,1333,1000)
canvas.configure(scrollregion=canvas.bbox("all"))
root.mainloop()

Advertisement

Answer

Scrollbars require two-way communication with the widgets they are controlling. You’ve properly configured the scrollbars but haven’t configured the canvas to update the scrollbars.

To do that, add the following code after you’ve defined the canvas and scrollbars:

canvas.configure(yscrollcommand=scroll_y.set, xscrollcommand=scroll_x.set)
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement