[英]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.我正在使用 Tkinter/Python 的 Canva 类的 coord() 方法来移动一个矩形。 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()
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欢迎来到 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.将 x 和 y 存储在元组中是一个问题,但也不提供 x2 和 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.
你不能在 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.