Problem with scrollbar in a Canvas, appears outside it

1

I'm trying to create a Canvas with a ScrollBar in order to load an image and manipulate it. I have the following code:

from tkinter import *
from tkinter import Tk    
from tkinter import PhotoImage
from tkinter import Canvas
from tkinter import NW
from tkinter import Menu
from tkinter import filedialog
from PIL import Image, ImageTk
from sys import argv
import tkinter as tk

ventana =Tk ()

ventana.geometry("900x900+0+0")
ventana.title("PRUEBA 1")
ventana.config(bg="#cdc9c9")

canvas = Canvas (ventana, height=400, width=600,bg='#faf0e6') 

scrollbar = tk.Scrollbar(ventana, command=canvas.yview)
scrollbar.pack(side=tk.LEFT, fill='y')
canvas.configure(yscrollcommand = scrollbar.set)
canvas.pack()

ventana.mainloop()

The problem is that the scroll bar is not inside the canvas, but is positioned on the edge of the window.

    
asked by Airam 08.02.2018 в 19:38
source

1 answer

0

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:

    
answered by 08.02.2018 / 21:37
source