The canvas needs to know what part of its larger virtual canvas should be accessible via scrolling. You do this by setting the scrollregion
attribute. The scrollregion
defines the coordinates of the upper-left and lower-right corners of the area to be scrollable.
For example, if you want the canvas to appear on the screen as a 500x700 area but want to scroll over to the right to see 2000x700, you should do this:
canvas.configure(scrollregion=(0,0,2000,700))
Note: it wasn't clear from your question how or if you were adding things to the canvas. The above example gives a fixed scrollregion
. The more common way is to define the scrollregion
after adding widgets by using bbox("all")
to get the bounding box of all of the objects on the canvas, like so:
canvas.configure(scrollregion=canvas.bbox("all"))
I am also wondering how can i make this scrollbar wider. I have only found how to make it taller but not wider.
That is controlled by the use of pack
or grid
. Also, the scrollbar shouldn't be a child of the canvas, it needs to use the same parent as the canvas.
Here is your code with the necessary changes. I've also changed the import statement to be PEP8 compliant, and added some tick marks so that you can see the canvas as it scrolls.
import tkinter as tk
root = tk.Tk()
canvas = tk.Canvas(root, bg="blue", height=700, width=500)
scrollbar = tk.Scrollbar(root, orient="horizontal", width=18, command=canvas.xview)
canvas.configure(scrollregion=(0,0,2000,700), xscrollcommand=scrollbar.set)
root.grid_rowconfigure(0, weight=1)
root.grid_columnconfigure(0, weight=1)
canvas.grid(column=0, row=0, sticky="nsew")
scrollbar.grid(row=1, column=0, sticky="ew")
# this adds tick-marks every 100 pixels so that you can
# see the canvas scroll
for x in range(0, 2001, 100):
anchor = "sw" if x < 100 else ("se" if x==2000 else "s")
canvas.create_line(x, 700, x, 690, fill="red")
canvas.create_text(x, 680, text=x, anchor=anchor)
root.mainloop()