1

我是 Python 新手。当我单击鼠标时,我需要编写一个程序来移动我的球或圆圈。我如何实现这一目标?我开始使用以下代码:

from graphics import *
import time

def MouseTracker():

win = GraphWin("MyWindow", 500, 500)
win.setBackground("blue")
cir = Circle(Point(250,250) ,20)
cir.setFill("red")
cir.draw(win)

while(win.getMouse() != None):
    xincr = 0
    yincr = 0
for i in range(7):
    cir.move(xincr, yincr)
    time.sleep(.2)
win.getMouse()
4

2 回答 2

0

假设您不受某些特定工具或实现的约束,您可能会发现 matplotlib 很有用。您可以使用圆形补丁( http://matplotlib.org/api/patches_api.html )在绘图区域上绘制一个圆形,然后在图形轴上单击鼠标时移动它。您将需要连接到事件单击侦听器并定义一个处理绘图更新​​的回调函数 -有关如何执行此操作的示例,请参见http://matplotlib.org/users/event_handling.html 。您可以使用 xdata 和 ydata 方法获取鼠标按下的坐标。

这在 python 2.7 中对我有用:

import matplotlib.pyplot as plt
from matplotlib.patches import Circle

fig = plt.figure()
ax = fig.add_subplot(111)
circ = Circle((0.5,0.5), 0.1)
ax.add_patch(circ)

def update_circle(event):
    ax.cla()
    circ = Circle((event.xdata, event.ydata), 0.1)
    ax.add_patch(circ)
    fig.canvas.draw()

fig.canvas.mpl_connect('button_press_event', update_circle)
plt.show()
于 2016-02-19T12:07:42.340 回答
0

假设您想坚持使用您开始使用的图形包,您可以这样做,但您缺少保存鼠标位置并将其与圆的中心位置进行比较的代码:

from graphics import *

WIDTH, HEIGHT = 500, 500
POSITION = Point(250, 250)
RADIUS = 20
STEPS = 7

def MouseTracker(window, shape):
    while True:
        position = window.getMouse()

        if position != None:  # in case we want to use checkMouse() later
            center = shape.getCenter()
            xincr = (position.getX() - center.getX()) / STEPS
            yincr = (position.getY() - center.getY()) / STEPS
            for _ in range(STEPS):
                shape.move(xincr, yincr)

win = GraphWin("MyWindow", WIDTH, HEIGHT)
win.setBackground("blue")

cir = Circle(POSITION, RADIUS)
cir.setFill("red")
cir.draw(win)

MouseTracker(win, cir)

您需要关闭窗口才能跳出跟踪循环——在实际程序中,您将把它作为设计的一部分来处理(即,某些用户操作会导致循环break中的一个while True:。)

于 2017-01-15T02:42:21.200 回答