这是我的类,允许用户拖动画布。
class WindowDraggable():
def __init__(self, label):
self.label = label
label.bind('<ButtonPress-1>', self.StartMove)
label.bind('<ButtonRelease-1>', self.StopMove)
label.bind('<B1-Motion>', self.OnMotion)
def StartMove(self, event):
self.x = event.x
self.y = event.y
def StopMove(self, event):
self.x = None
self.y = None
def OnMotion(self, event):
x = (event.x_root - self.x - self.label.winfo_rootx()
+ self.label.winfo_rootx())
y = (event.y_root - self.y - self.label.winfo_rooty()
+ self.label.winfo_rooty())
root.geometry("+%s+%s" % (x, y))但是,一旦我单击并持有标签,随后的运动将调整画布的位置,使光标定位在画布的左上角。您可以看到光标在此图像中的位置。

我想用建议手动设置光标位置来解决这个问题
def StartMove(self, event):
self.x = event.x + 100
self.y = event.y + 150但问题是标签会扩展到屏幕的两侧,因此光标应该保持原来的位置,这是出于美学的原因。我发现了这个函数,认为它有助于解决问题,但我有点迷失在如何使用它。
#sets mouse-cursor position
def click(x,y):
win32api.SetCursorPos((x,y))
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,x,y,0,0)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,x,y,0,0)这是我的简化程序,只显示了与我的问题相关的基本部分。
from tkinter import *
from PIL import ImageTk, Image
#window creation
root = Tk()
root.overrideredirect(1) # eliminates frame around window
#canvas creation
canvas = Canvas(root, width=width, height=height, bd=-2)
canvas.pack()
#sets mouse-cursor position
def click(x,y):
win32api.SetCursorPos((x,y))
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,x,y,0,0)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,x,y,0,0)
#makes window draggable
class WindowDraggable():
def __init__(self, label):
self.label = label
label.bind('<ButtonPress-1>', self.StartMove)
label.bind('<ButtonRelease-1>', self.StopMove)
label.bind('<B1-Motion>', self.OnMotion)
def StartMove(self, event):
self.x = event.x + 100
self.y = event.y + 150
def StopMove(self, event):
self.x = None
self.y = None
def OnMotion(self, event):
x = (event.x_root - self.x - self.label.winfo_rootx()
+ self.label.winfo_rootx())
y = (event.y_root - self.y - self.label.winfo_rooty()
+ self.label.winfo_rooty())
root.geometry("+%s+%s" % (x, y))
#creates the draggable label
label = Label(root, text='drag me')
WindowDraggable(label)
label.pack(fill=BOTH, expand=1)
#end of program
root.mainloop()发布于 2014-11-20 18:01:08
听起来,您只需要做一次,这样当您设置画布的新位置时,您需要从x中取掉画布宽度的一半,并将画布的一半高添加到为什么:
def StartMove(self, event):
self.x = event.x - (width / 2)
self.y = event.y + (height / 2)https://stackoverflow.com/questions/27045248
复制相似问题