I´ve found some questions about similar problems. But not right the same like my problem.
If my mouse is moved left or right or down all works fine. But if I move the mouse fast up the x y position is sometimes wrong! To describe the problem in the best way I have a short video for you. If I move the mouse very slow up there is no problem. Why? Left, right and down the mouse speed there is no problem.
Here is my python code:
import tkinter as tk
root = tk.Tk()
root.geometry('2000x600')
# Textausgabe erzeugen
label1 = tk.Label(root, text="Hallo Welt!",
fg="red",
bg="orange",
font=("times", 25, "bold", "italic"))
label1.place(x=1, y=1)
#Grafik einbetten
bild1 = tk.PhotoImage(file="biene.png")
label2 = tk.Label(root, image=bild1)
label2.place(x=1,y=100)
def motion(event):
global pos_x, pos_y, r_pos_x, r_pos_y
pos_x = event.x
pos_y = event.y
label2.place(x=pos_x-60,y=pos_y-110)
print('{}, {}'.format(pos_x, pos_y))
CodePudding user response:
(event.x, event.y)
is the coordinate of the mouse at the time of the event, relative to the upper left corner of the widget. You may also get the coordinate in the widgets label1 or label2.
Try to use (event.root_x, event.root_y)
which is the coordinate of the mouse at the time of the event, relative to the upper left corner of the screen.
import tkinter as tk
root = tk.Tk()
root.geometry('1000x600')
# Textausgabe erzeugen
label1 = tk.Label(root, text="Hallo Welt!",
fg="red",
bg="orange",
font=("times", 25, "bold", "italic"))
label1.place(x=1, y=1)
#Grafik einbetten
bild1 = tk.PhotoImage(file="biene.png")
label2 = tk.Label(root, image=bild1)
label2.place(x=1, y=100)
def motion(event):
global pos_x, pos_y, r_pos_x, r_pos_y
pos_x = event.x_root # Revised
pos_y = event.y_root # Revised
label2.place(x=pos_x-60, y=pos_y-110)
print(event.widget) # Check which widget
print('{}, {}'.format(pos_x, pos_y))
root.bind("<Motion>", motion)
root.mainloop()
CodePudding user response:
here is my solution. Thanks to all.
from tkinter import *
canvas_width = 2000
canvas_height =600
master = Tk()
master.geometry('2000x600')
image1 = "biene.png"
photo1 = PhotoImage(file=image1)
width1 = photo1.width()
height1 = photo1.height()
canvas1 = Canvas(width=width1, height=height1)
canvas1.pack(expand=1, fill=BOTH) # <--- Make your canvas expandable.
x = (width1)/2.0
y = (height1)/2.0
item = canvas1.create_image(x, y, image=photo1)
def motion(event):
global pos_x, pos_y
global item
global item_x, item_y
item_pos = canvas1.coords(item)
item_x = item_pos[0]
item_y = item_pos[1]
#print("item pos = " str(item_x) " " str(item_y))
pos_x = event.x
pos_y = event.y
canvas1.move(item, pos_x - item_x, pos_y - item_y) # <--- Use Canvas.move method.
#canvas1.delete(item)
#item = canvas1.create_image(pos_x, pos_y, image=photo1)
print('{}, {}'.format(pos_x, pos_y))
print("Coordinates of the object are:", canvas1.coords(item))
master.bind('<Motion>', motion)
mainloop()