简体   繁体   中英

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

The coordinate keeps printing None. How can I get the coordinates of the win.checkMouse() when the window has been pressed?

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

Try this.

checkMouse() function returns last mouse click or None if mouse has not been clicked since last call. So it makes clicked value to None while exiting the while loop.

You forgot () in first win.checkMouse()

In your example you have to click twice because first click (and coordinates) is catched by first win.checkMouse() in while loop. Second click will be catched by 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()

EDIT: Example without 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()

EDIT: binding function to mouse buttons

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM