使用graphics.py(Zelle(和Python时,是否存在事件侦听器?
对于turtle
图形,存在:onkeypress
。有了pygame
,就有了:if event.key == pygame.K_w:
。
我希望使用graphics.py
能找到类似的工作方式。
正如我在评论中所说,你可以使用setMouseHandler()
来监听鼠标点击,但实际上并没有按键的功能——不过你可以通过循环调用checkMouse()
来伪造它(这可能消除了破解graphics.py
的必要(。从你最近的评论中,我看到你可能是自己发现的。。。
无论如何,值得一提的是,这里有一个简单的演示,说明了我的意思:
from graphics import*
import time
def my_mousehandler(pnt):
print(f'clicked: ({pnt.x}, {pnt.y})')
def my_keyboardhandler(key):
print(f'key press: {key!r}')
def main():
win = GraphWin("window", 300,400)
win.setMouseHandler(my_mousehandler) # Register mouse click handler function.
txt = Text(Point(150, 15), "Event Listener Demo")
txt.setSize(15)
txt.draw(win)
txt.setStyle("bold")
txt.setTextColor("red")
while True:
win.checkMouse() # Return value ignored.
try:
key = win.checkKey()
except GraphicsError:
break # Window closed by user.
if key:
my_keyboardhandler(key)
time.sleep(.01)
if __name__ == '__main__':
main()