2

I am fairly new to tkinter and I've been working on this feature of my project that allows a user to drag and drop canvas objects around, however when I move around the canvas and try to move the canvas object again, it behaves weirdly. It's somewhat hard to explain so I left a video below for context and the code as well. Any kind of help is appreciated :)

import customtkinter

from tkinter import Canvas
from PIL import Image, ImageTk



def move(event):
    my_canvas.moveto(my_image,event.x-50,event.y-50)

def scan(event):
    my_canvas.scan_mark(event.x, event.y)

def drag(event):
    my_canvas.scan_dragto(event.x, event.y, gain=2)

def display_coords(event):
    my_label.configure(text=f"X: {event.x} Y:{event.y}")



app = customtkinter.CTk()


frame1 = customtkinter.CTkFrame(master=app)
frame1.pack(padx=10,pady=10, expand=True, fill="both")

my_canvas = Canvas(master=frame1, height=100, width=100, bg="black")
my_canvas.pack(expand=True, fill="both")

#Resize image(originally 512 x 512)
img = Image.open("assets/computadora.png")
resized_image = img.resize((100,100))
image = ImageTk.PhotoImage(resized_image)
frame1.image = image
my_image = my_canvas.create_image(0, 0, image=image, anchor="nw")


my_canvas.tag_bind(my_image,"<Button1-Motion>", move, add="+")
my_canvas.bind("<Button-3>", scan)
my_canvas.bind("<Button3-Motion>", drag)


#Provides X-Y coordinates of mouse cursor when canvas object is selected
my_label = customtkinter.CTkLabel(master=my_canvas, text="X: None Y: None")
my_label.pack(padx="10px", pady="10px", anchor="se")
my_canvas.tag_bind(my_image, "<Button1-Motion>", display_coords, add="+")


my_canvas.configure(scrollregion=my_canvas.bbox(my_image))


app.mainloop()

here

Cyberin
  • 33
  • 4
  • What is `customtkinter` since we cannot test your code without it? – Mike - SMT Nov 30 '22 at 13:56
  • @Mike-SMT [customtkinter](https://github.com/TomSchimansky/CustomTkinter). It's essentially a themed "fork" of tkinter. – JRiggles Nov 30 '22 at 13:58
  • 4
    After calling `drag()`, the top-left corner of the canvas is not (0, 0) anymore. So `event.x` and `event.y` will not the same as the real coordinates in the canvas. You need to use `my_canvas.canvasx()` and `my_canvas.canvasy()` to convert the `event.x` and `event.y` to the real coordinate `x` and `y`. – acw1668 Nov 30 '22 at 14:26

0 Answers0