1
我想知道当我将<Motion>
事件绑定到函数时,如果在该函数中我可以使用pygame的mouse.get_rel()
版本定义x
和y
变量,但在tkinter中。类似于tkinter中pygame的get_rel()的命令?
我想知道当我将<Motion>
事件绑定到函数时,如果在该函数中我可以使用pygame的mouse.get_rel()
版本定义x
和y
变量,但在tkinter中。类似于tkinter中pygame的get_rel()的命令?
事件的处理是不同的tkinter
比pygame
,所以不是直接mouse.get_rel()
等同,它似乎更适合创造的东西,将每一个鼠标移动时(这是结合'<Motion>'
事件完成)调用回调函数。为了帮助做到这一点,RelativeMotion
类定义为隐藏和封装尽可能多的混乱细节。远远低于它运行的屏幕截图。
import tkinter as tk
class RelativeMotion(object):
""" Relative mouse motion controller. """
def __init__(self, callback):
self.__call__ = self._init_location # first call
self.callback = callback
def __call__(self, *args, **kwargs):
# Implicit invocations of special methods resolve to instance's type.
self.__call__(*args, **kwargs) # redirect call to instance itself
def _init_location(self, event):
self.x, self.y = event.x, event.y # initialize current position
self.__call__ = self._update_location # change for any subsequent calls
def _update_location(self, event):
dx, dy = event.x-self.x, event.y-self.y
self.x, self.y = event.x, event.y
self.callback(dx, dy)
class Application(tk.Frame): # usage demo
def __init__(self, master=None):
tk.Frame.__init__(self, master)
self.grid()
self.createWidgets()
self.relative_motion = RelativeMotion(self.canvas_mouse_motion)
self.canvas.bind('<Motion>', self.relative_motion) # when over canvas
def createWidgets(self):
self.motion_str = tk.StringVar()
self.canvas_mouse_motion(0, 0) # initialize motion_str text
label_width = len(self.motion_str.get())
self.motion_lbl = tk.Label(self, bg='white', width=label_width,
textvariable=self.motion_str)
self.motion_lbl.grid(row=0, column=0)
self.quit_btn = tk.Button(self, text='Quit', command=self.quit)
self.quit_btn.grid(row=1, column=0)
self.canvas = tk.Canvas(self, width='2i', height='2i', bg='white')
self.canvas.grid(row=1, column=1)
def canvas_mouse_motion(self, dx, dy):
self.motion_str.set('{:3d}, {:3d}'.format(dx, dy))
app = Application()
app.master.title('Relative Motion Demo')
app.mainloop()
运行
是什么'event.get_rel()'做什么?我没有在[documentation](http://www.pygame.org/docs/ref/event.html)中看到它。 – martineau
你可以得到事件的x,y。您可以获取窗口相对于窗口的x.y,并且可以获取窗口的x,y。从那里只有一点点数学。 –
@martineau对不起,它是mouse.get_rel() –