我想知道当我将<Motion>
事件绑定到函数时,如果在该函数中我可以使用pygame的{{1}版本定义x
和y
变量},但在tkinter。
答案 0 :(得分:0)
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()
<强>运行强>