Logically the ScrollBar
appears in its parent widget, in this case ventana
. You can not position a ScrollBar
in the canvas directly, what you can do is use a Frame
extra as a container and group the canvas and ScrollBar
.
It is necessary to take into account a special feature of Canvas
, the space of coordinates of the canvas does not have limits , in each moment only a very small fraction of the space of available coordinates is visible.
To solve this, simply limit the displacement to a certain area by config(scrollregion=(0, 0, width, height)
, in this case the size of the image).
from sys import argv
from PIL import Image, ImageTk
import tkinter as tk
from tkinter import filedialog
ventana = tk.Tk ()
ventana.geometry("900x900+0+0")
ventana.title("PRUEBA 1")
ventana.config(bg="#cdc9c9")
img_frame = tk.Frame(ventana, height=400, width=600, bg='#faf0e6')
img_frame.pack()
canvas = tk.Canvas (img_frame, height=400, width=600, bg='#faf0e6', relief=tk.SUNKEN)
sbarV = tk.Scrollbar(img_frame, orient=tk.VERTICAL, command=canvas.yview)
sbarH = tk.Scrollbar(img_frame, orient=tk.HORIZONTAL, command=canvas.xview)
sbarV.pack(side=tk.RIGHT, fill=tk.Y)
sbarH.pack(side=tk.BOTTOM, fill=tk.X)
canvas.config(yscrollcommand=sbarV.set)
canvas.config(xscrollcommand=sbarH.set)
canvas.pack(side=tk.LEFT, expand=True, fill=tk.BOTH)
img_path = filedialog.askopenfilename(initialdir = "/", title = "Select file",
filetypes = (("jpeg files","*.jpg"),
("all files","*.*")))
img = Image.open(img_path)
width, height = img.size
canvas.config(scrollregion=(0, 0, width, height))
img2 = ImageTk.PhotoImage(img)
imagesprite = canvas.create_image(0, 0, anchor="nw", image=img2)
ventana.mainloop()
This shows us the image within our Canvas
with two ScrollBars
to be able to move: