Creating a scrollbar for canvas window is really hard to achieve with Tkinter.I somehow managed to create a vertical scrollbar but now I have no idea to create a horizontal scrollbar. If possible please share sample code for creating a double frame for canvas window.
Asked
Active
Viewed 129 times
-16
-
Does this answer your question? [Vertical and Horizontal Scrollbars on Tkinter Widget](https://stackoverflow.com/questions/9561030/vertical-and-horizontal-scrollbars-on-tkinter-widget) – Thingamabobs Mar 15 '21 at 16:18
-
[What about this tutorial?](https://tkdocs.com/tutorial/canvas.html#scrolling) – Thingamabobs Mar 15 '21 at 16:20
-
Creating a horizontal scrollbar is virtually identical to creating a vertical one. Please show what you've tried. Also, "a double frame for canvas window" doesn't make much sense. What is a "double frame"? – Bryan Oakley Mar 15 '21 at 16:31
-
Atlas435 it kind of does thanks – Dhrutiman Bhattacharjee Mar 15 '21 at 16:33
1 Answers
4
Normally I don't give answers to questions that show no signs of research or experimentation, but it's clear you're struggling. Here's an example of a 1000x1000 canvas in a 500x500 window, with some random rectangles to illustrate that the scrolling works.
import tkinter as tk
import random
root = tk.Tk()
canvas = tk.Canvas(root, width=500, height=500, scrollregion=(0,0,999,999), bg="black")
vsb = tk.Scrollbar(root, orient="vertical", command=canvas.yview)
hsb = tk.Scrollbar(root, orient="horizontal", command=canvas.xview)
canvas.configure(yscrollcommand=vsb.set, xscrollcommand=hsb.set)
root.grid_rowconfigure(0, weight=1)
root.grid_columnconfigure(0, weight=1)
vsb.grid(row=0, column=1, sticky="ns")
hsb.grid(row=1, column=0, sticky="ew")
canvas.grid(row=0, column=0, sticky="nsew")
for i in range(100):
color = random.choice(("red", "orange", "yellow", "green", "blue", "violet"))
width = random.randint(20, 100)
height = random.randint(20, 100)
x0 = random.randint(10, 990-width)
y0 = random.randint(10, 990-height)
canvas.create_rectangle(x0, y0, x0+width, y0+height, outline='white', fill=color)
root.mainloop()

Bryan Oakley
- 370,779
- 53
- 539
- 685