0

I'm having problems with a Zoom function. The problem is, that instead of the picture enlarging it moves. This is not what I what but I can't figure out what's wrong.

Here is the code I have written so far. Moving the image with the mouse works fine it's just the Zooming that isn't working. I taking the problem is in the weel(event) function:

import tkinter as tk
from tkinter import ttk, Canvas, PhotoImage, Label
from PIL import Image, ImageTk
root = tk.Tk()
root.title('Codemy.com')
root.geometry("1100x700")

w = 1000
h = 676
x = w/2
y = h/2
my_canvas = Canvas(root, width=w, heigh=h)
my_canvas.pack(pady=20)

# Add Image To Canvas
img = PhotoImage(file="C:/Users/bodig/Desktop/mario-clip-art-5.png")#Path to image
my_image = my_canvas.create_image(260,125, image=img)

def move(event):
    global img
    img = PhotoImage(file="C:/Users/bodig/Desktop/mario-clip-art-5.png")#Path to image
    my_image = my_canvas.create_image(event.x,event.y, image=img)

def wheel(event):
    x = my_canvas.canvasx(event.x)
    y = my_canvas.canvasy(event.y)
    scale = 1.0
    imscale = 1.0
    delta = 1.3
    # Respond to (event.delta) wheel event
    if event.delta == -120:  # scroll down
        imscale /= delta
        scale        /= delta
    if event.delta == 120:  # scroll up
        imscale *= delta
        scale        *= delta
    my_canvas.scale('all', x, y, scale, scale)  # rescale all canvas objects

my_label = Label(root, text="")
my_label.pack(pady=20)

my_canvas.bind('<B1-Motion>', move)
my_canvas.bind('<MouseWheel>', wheel)
root.mainloop()
G Force
  • 27
  • 4
  • 1
    Try checking this guy's code: (https://stackoverflow.com/questions/5436810/adding-zooming-in-and-out-with-a-tkinter-canvas-widget). – Sten Healey Jan 03 '22 at 14:47

1 Answers1

0

The problem is, that instead of the picture enlarging it moves. This is not what I what but I can't figure out what's wrong.

There is nothing wrong. This is the documented behavior of the canvas. From the documentation on scale:

Note that some items have only a single pair of coordinates (e.g., text, images and windows) and so scaling of them by this command can only move them around.

Similar questions have been asked before. This question has an answer with an implementation you might find useful: Tkinter canvas zoom + move/pan

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