2016-02-19 37 views
1

我是Python新手。當我點擊鼠標時,我需要編寫一個程序來移動我的球或圓圈。我如何實現這一目標?我有下面的代碼,我開始有:使用Zelle在Python中進行getMouse跟蹤graphics.py

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() 

回答

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() 
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) 

您需要關閉該窗口跳出跟蹤環路 - 在一個真正的程序你會處理這個作爲設計的一部分(即某個用戶操作導致breakwhile True:循環中。)