Python graphics.py。如何获得checkMouse()的返回?

时间:2016-11-17 11:39:29

标签: python graphics zelle-graphics

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

坐标保持打印无。如何在按下窗口时获取win.checkMouse()的坐标?

2 个答案:

答案 0 :(得分:1)

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()函数返回上次鼠标单击或如果自上次调用后未单击鼠标,则返回None。因此,当退出while循环时,它会将clicked值设置为None。

答案 1 :(得分:0)

您在第一个()

中忘记了win.checkMouse()

在您的示例中,您必须单击两次,因为首先单击(和坐标)会被win.checkMouse()循环中的第一个while捕获。第二次点击将由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()