簡體   English   中英

如何獲得方向<Motion>在 tkinter 中?

[英]How to get the direction of <Motion> in tkinter?

我正在嘗試獲取 tkinter <Motion> (實際上是<B1-Motion> )事件的方向。

我已經嘗試使用event.direction (error), event.keysym (??) 和 event 本身給了我一些坐標。

所以這是我到目前為止的代碼:

def holdanddrag(event):
    print('Direction: '+event.   … ) # here I need some help
Widget.bind('<B1-Motion>', holdanddrag)

有誰知道該怎么做? 提前致謝!

為了確定方向,您必須存儲previous position ,並使用它來計算到actual position的運動方向(歸一化向量)。 這些變量必須在運動發生時更新。

下面是一個小例子,在畫布上繪制一個與鼠標拖動方向對應的向量(箭頭):

在此處輸入圖片說明

import math
import tkinter as tk
from collections import deque


class Vector:
    """small class for vector arithmetic convenience
    """ 
    def __init__(self, x: float=0, y: float=0) -> None:
        self.x = x
        self.y = y
    def __str__(self) -> str:
        return f'({self.x}, {self.y})'
    def __mul__(self, scalar: float) -> 'Vector':
        return Vector(self.x * scalar, self.y * scalar)
    def magnitude(self) -> float:
        return math.hypot(self.x, self.y)
    def normalize(self) -> 'Vector':
        mag = self.magnitude()
        return Vector(self.x / mag, self.y / mag) if mag != 0 else Vector()
    def __repr__(self) -> str:
        return str(self)
    def __iter__(self) -> float:
        yield self.x
        yield self.y


class Point:
    """small class for point arithmetic convenience
    """ 
    def __init__(self, x: float, y: float):
        self.x = x
        self.y = y        
    def __sub__(self, other: 'Point') -> Vector:
        return Vector(other.x - self.x, other.y - self.y)
    def __add__(self, vec: Vector) -> 'Point':
        return Point(self.x + vec.x, self.y + vec.y)
    def __str__(self) -> str:
        return f'({self.x}, {self.y})'
    def __repr__(self) -> str:
        return str(self)
    def __iter__(self) -> float:
        yield self.x
        yield self.y

def draw_dir(canvas, start_point: Point, _vid=[None]) -> None:
    """draws and updates the scaled normalized direction vector
    on the canvas.
    Keeps track of the id of the canvas item last drawn 
    """
    if _vid[0] is not None:
        canvas.delete(_vid[0])
    normed_scaled_v = direct.normalize() * -50
    end_point = start_point + normed_scaled_v
    _vid[0] = canvas.create_line(*start_point, *end_point, arrow=tk.LAST)

_maxlen = 4

def direction(event, _direct=deque([Vector(0, 0) for _ in range(_maxlen)], maxlen=_maxlen)) -> None:
    """stores previous position, and uses it to calculate the direction
    from the current position.
    updates these variables
    """
    global direct
    _direct.append(Point(event.x, event.y))
    p0, p1 = _direct[0], _direct[-1]
    direct = p1 - p0
    draw_dir(canvas, p1)    
#     print(_direct, direct)

direct = Vector(0, 0)

root = tk.Tk()
canvas = tk.Canvas(root, bg='cyan')
canvas.pack()
canvas.bind('<B1-Motion>', direction)
root.mainloop()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM