I am a complete beginner in pyglet. I would like to have a local variable "state", and let certain events be executed only if the state is correct. This way, pyglet lets me write that label with on_text, but when I press backspace or enter it tells me that local variable "state" is referenced before assignment. It has something to do with that pyglet.window.key.TAB, because when I remove it, it works. What did I do wrong?
def run_application():
window = pyglet.window.Window()
state = "choose map" #in which "part" of the oplication we are right now
racetrack_name = pyglet.text.Label("", x=10, y=20)
print(state)
@window.event
def on_key_press(key_code, modifier):
#OPEN menu
if key_code == pyglet.window.key.TAB:
state = "menu"
#remove text when in "choose map"
if key_code == pyglet.window.key.BACKSPACE and state == "choose map":
racetrack_name.text = racetrack_name.text[:-1]
elif key_code == pyglet.window.key.ENTER:
if state == "choose map":
print(racetrack_name)
@window.event
def on_text(text):
if state == "choose map":
racetrack_name.text = racetrack_name.text + text
@window.event
def on_draw():
global state
window.clear()
racetrack_name.draw()
pyglet.app.run()
return
run_application()
Edit - full error traceback:
Exception ignored on calling ctypes callback function: <function Win32Window._get_window_proc.<locals>.f at 0x000001862D0644C0>
Traceback (most recent call last):
File "C:\Users\ondra\AppData\Local\Programs\Python\Python39\lib\site-packages\pyglet\window\win32\__init__.py", line 747, in f
result = event_handler(msg, wParam, lParam)
File "C:\Users\ondra\AppData\Local\Programs\Python\Python39\lib\site-packages\pyglet\window\win32\__init__.py", line 819, in _event_key
self.dispatch_event(ev, symbol, modifiers)
File "C:\Users\ondra\AppData\Local\Programs\Python\Python39\lib\site-packages\pyglet\window\__init__.py", line 1352, in dispatch_event
if EventDispatcher.dispatch_event(self, *args) != False:
File "C:\Users\ondra\AppData\Local\Programs\Python\Python39\lib\site-packages\pyglet\event.py", line 408, in dispatch_event
if handler(*args):
File "C:\Users\ondra\AppData\Local\Temp\ipykernel_5256\3428602759.py", line 22, in on_key_press
UnboundLocalError: local variable 'state' referenced before assignment