简体   繁体   中英

How to move a rectangle to the mouse position with Tkinter/Python?

I'm using Tkinter/Python's Canva class' coord() method to move a rectangle. What should I pass as paramters in order to make it work?

from tkinter import *

root = Tk()

def key(event):
    print ("pressed", repr(event.char))

def callback(event):
    position = (event.x,event.y)
    event.widget.coords(item, position)

canvas= Canvas(root, width=100, height=100)
canvas.bind("<Key>", key)
canvas.bind("<Button-1>", callback)
item = canvas.create_rectangle(10,10,5,5)
canvas.pack()

move widget using mouse

from tkinter import *
import pyautogui
 
def on_move(event):
    component=event.widget
    locx, locy = component.winfo_x(), component.winfo_y()
    w , h =master.winfo_width(),master.winfo_height()
    mx ,my =component.winfo_width(),component.winfo_height()
    xpos=(locx+event.x)-(15)
    ypos=(locy+event.y)-int(my/2)
    if xpos>=0 and ypos>=0 and w-abs(xpos)>=0 and h-abs(ypos)>=0 and xpos<=w-5 and ypos<=h-5:
       component.place(x=xpos,y=ypos)

 
master = Tk()
master.geometry("%dx%d+0+0" % (500,500))
msg = Label(master, text = "Click & Move")
msg.config(bg='lightgreen', font=('times', 24, 'italic'))
msg.bind('<B1-Motion>',on_move)
msg.place(x=10,y=20)
mainloop()

This seems your first post. Welcome to SO :D

Updated answer: After some research and testing, it seems that you just need to pass the coordenates without the tuple. Storing x and y in a tuple is a problem, but also not providing the values for x2 and y2.

def callback(event):
    event.widget.coords(item, event.x + 5, event.y + 5, event.x, event.y)

You can learn more here

Original wrong answer:
You can't move items on tk. Maybe try to clean the canvas and create the item at the new coordinates.

canvas.delete("all")
canvas.create_rectangle(event.x + 5,event.y + 5, position)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM