jan novotný
jan novotný

Reputation: 138

How to close a pyglet window?

I have a following problem. Suppose I have a following code:

@window.event
def on_key_press( symbol, mod):
    if condition == True:
       return print("Game over")

pyglet.app.run()

I need to also to close the window after the condition == True is met. How can I do that please? I tried:

@window.event
def on_key_press( symbol, mod):
    if condition == True:
       return print("Game over")
       pyglet.app.exit()

but it did not work. Thanks a lot for any help!

Upvotes: 3

Views: 601

Answers (2)

Apostolos
Apostolos

Reputation: 3467

This is an old topic. But for those who work with pyglet 2.0.x (2.0.15 more specifically in my case), a solution is tu issue window_close() (As per https://pyglet.readthedocs.io/en/latest/modules/window.html). The following example created a keyboard listener that shows the symbol of the key pressed and its modifiers, until [Esc] or [Q] is pressed:

import pyglet
from pyglet.window import key
keys = key.KeyStateHandler()

window = pyglet.window.Window()

@window.event
def on_key_press(symbol, modifiers):
  print(symbol,modifiers,end=' | ',flush=True)
  if symbol in [key.Q, key.ESCAPE]:
    print("\nExit key pressed")
    window.close()

window.push_handlers(keys)
pyglet.app.run()

Upvotes: 0

Rabbid76
Rabbid76

Reputation: 211219

The function is terminated at the the first occurrence of return in the control flow. You have to remove the return statement.

@window.event
def on_key_press( symbol, mod):
    if condition == True:

       # return print("Game over") <--- DELETE
       
       print("Game over")

       pyglet.app.exit()

Upvotes: 1

Related Questions