1

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.

martineau
  • 119,623
  • 25
  • 170
  • 301
netrate
  • 423
  • 2
  • 8
  • 14
  • 1
    `if event.key == pygame.K_w:` is not an event listener. It's explicitly checking the type of an event object (possibly after retrieving it from the event queue via `pygame.event.get()`). Zelle has something called `checkKey()` which will return the last key pressed or `""` if none have been pressed since the last call (but that's not a "listener" either). – martineau Jun 07 '21 at 02:50
  • Thank you for sending me in the right direction, I did find something that has the checkley() and works quite well. https://www.cs.swarthmore.edu/courses/CS21Book/ch08.html#chapter-catch – netrate Jun 07 '21 at 03:47

1 Answers1

2

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()
martineau
  • 119,623
  • 25
  • 170
  • 301
  • I want to thank you. You seem to be the only person that reaches out and help when it comes to the Zelle graphics and Python material. It is appreciated. – netrate Jun 07 '21 at 18:24