简体   繁体   中英

Is there an event listener in the Zelle graphics module?

Is there an event listener when using graphics.py (Zelle) and Python?

With turtle graphics there is: onkeypress . With pygame there is: if event.key == pygame.K_w: .

I am hoping to find something that will work in a similar manner using graphics.py .

As I said in a comment you can use setMouseHandler() to listen for mouse-clicks, but there really isn't something existing for key-presses — however you can kind of fake it by calling checkMouse() in a loop (which might eliminate the need to hack graphics.py ). From what you said in a recent comment, I see you may have discovered this by yourself...

Anyhow, for what it's worth, here a simple demo illustrating what I meant:

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

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