Python graphics.py。如何获取checkMouse()的return?

Python graphics.py. How to get the return of checkMouse()?

win=GraphWin("test",410,505)

while win.checkMouse==None:
    rectangle=Rectangle(Point(100,100),Point(300,300))
    rectangle.draw(win)
    rectangle.undraw()
coordinate=win.checkMouse()

坐标不断打印None。当按下 window 时,如何获取 win.checkMouse() 的坐标?

你在第一个 win.checkMouse()

中忘记了 ()

在您的示例中,您必须单击两次,因为第一次单击(和坐标)被 while 循环中的第一个 win.checkMouse() 捕获。第二次点击将被 coordinate = win.checkMouse()

捕获
from graphics import *
import time

win = GraphWin("test", 410, 505)

while not win.checkMouse():
    rectangle = Rectangle(Point(100, 100), Point(300, 300))
    rectangle.draw(win)
    rectangle.undraw()

# time for second click
time.sleep(2)

coordinate = win.checkMouse()
print("coordinate:", coordinate)

win.close()

编辑: 没有 sleep()

的例子
from graphics import *

win = GraphWin("test", 410, 505)

rectangle = Rectangle(Point(100, 100), Point(300, 300))
rectangle.draw(win)

while True:
    coordinate = win.checkMouse()
    if coordinate:
        print("coordinate:", coordinate)
        break

win.close()

编辑: 鼠标按钮的绑定函数

from graphics import *

# --- functions ---

def on_click_left_button(event):
    x = event.x
    y = event.y
    rectangle = Rectangle(Point(x, y), Point(x+100, y+100))
    rectangle.draw(win)

def on_click_right_button(event):
    win.close()
    win.quit()

# --- main ---

win = GraphWin("test", 410, 505)

win.bind('<Button-1>', on_click_left_button)
win.bind('<Button-3>', on_click_right_button)

win.mainloop()
win=GraphWin("test",410,505)

coordinate = win.checkMouse()
while coordinate == None:
    rectangle=Rectangle(Point(100,100),Point(300,300))
    rectangle.draw(win)
    rectangle.undraw()
    coordinate = win.checkMouse()
print coordinate

试试这个。

checkMouse() 函数 returns 上次鼠标单击或 None 如果自上次调用以来未单击鼠标。因此它在退出 while 循环时将点击值设置为 None。