首页 > 解决方案 > Zelle 图形模块中是否有事件监听器?

问题描述

使用 graphics.py (Zelle) 和 Python 时是否有事件监听器?

turtle图形有:onkeypress. 有pygameif event.key == pygame.K_w:

我希望找到可以使用graphics.py.

标签: pythonkeylistenerzelle-graphics

解决方案


正如我在评论中所说,您可以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()

推荐阅读