PYGLET – Key State Handler

In this article, we will see how we can create a key state handler object in PYGLET module in python. Pyglet is easy to use but powerful library for developing visually rich GUI applications like games, multimedia, etc. A window is a “heavyweight” object occupying operating system resources. Windows may appear as floating regions or can be set to fill an entire screen (fullscreen). Key state handler class is a simple handler that tracks the state of keys on the keyboard. If a key is pressed then this handler holds a True value for it.
We can create a window with the help of command given below
# creating a window window = pyglet.window.Window(width, height, title)
In order to create window we use pyglet.window.key.KeyStateHandler method
Syntax : pyglet.window.key.KeyStateHandler()
Argument : It takes no argument
Return : It returns KeyStateHandler object
Below is the implementation
Python3
# importing pyglet module import pyglet import pyglet.window.key # width of window width = 500 # height of window height = 500 # caption i.e title of the window title = "Geeksforzambiatek" # creating a window window = pyglet.window.Window(width, height, title) # text text = "Welcome tozambiatek Have a nice day" # batch object batch = pyglet.graphics.Batch() # creating document document = pyglet.text.document.FormattedDocument(text) # setting style to the document document.set_style(0, len(document.text), dict( font_name ='Arial', font_size = 16, color =(255, 255, 255, 255))) # creating a incremental text layout layout = pyglet.text.layout.IncrementalTextLayout( document, 400, 350, batch = batch) # making layout to display multilinelayout.multiline = True # creating a caret caret = pyglet.text.caret.Caret(layout, color =(255, 255, 255)) # caret to window push handlers window.push_handlers(caret) # setting caret style caret.set_style(dict(font_name ="Arial")) # on draw event @window.event def on_draw(): # clear the window window.clear() # draw the batch batch.draw() # caret to window push handlers window.push_handlers(caret) # creating a key state handlerkey_handler = pyglet.window.key.KeyStateHandler() # key press event @window.event def on_key_press(symbol, modifier): # key "C" get press if symbol == pyglet.window.key.C: # printing the message print("Key : C is pressed") # image for icon img = image = pyglet.resource.image("gfg.png") # setting image as icon window.set_icon(img) # start running the application pyglet.app.run() |
Output :
Key : C is pressed Key : C is pressed



