简体   繁体   中英

Do something while the button is pressed in Python pyglet

@win.event
def on_key_press(key, modifiers):
    if key == pyglet.window.key.UP:
        print("UP")

This function print UP just one time, but I want to print UP while I am holding the button UP.

You would need to do this check outside of the on_key_press .
Since that function is a one-shot function called only when a key DOWN event is triggered. And that trigger is only executed once from the operating system.

So you would need to save a DOWN state ( on_key_press ) and save the pressed key in a variable some where (below, I call this self.keys ) .
Subsequently, you also need to take care of any RELEASE events, which in my example below is done in on_key_release .

Here's how that could all tie together:

from pyglet import *
from pyglet.gl import *

key = pyglet.window.key

class main(pyglet.window.Window):
    def __init__ (self, width=800, height=600, fps=False, *args, **kwargs):
        super(main, self).__init__(width, height, *args, **kwargs)

        self.keys = {}

        self.alive = 1

    def on_draw(self):
        self.render()

    def on_close(self):
        self.alive = 0

    def on_key_release(self, symbol, modifiers):
        try:
            del self.keys[symbol]
        except:
            pass

    def on_key_press(self, symbol, modifiers):
        if symbol == key.ESCAPE: # [ESC]
            self.alive = 0

        self.keys[symbol] = True

    def render(self):
        self.clear()

        ## Add stuff you want to render here.
        ## Preferably in the form of a batch.

        self.flip()

    def run(self):
        while self.alive == 1:
            # -----------> This is key <----------
            # This is what replaces pyglet.app.run()
            # but is required for the GUI to not freeze
            #
            event = self.dispatch_events()

            if key.UP in self.keys:
                print('Still holding UP')
            self.render()

if __name__ == '__main__':
    x = main()
    x.run()

Seems like pyglet introduced an event handler for this use case: https://pyglet.readthedocs.io/en/latest/programming_guide/keyboard.html#remembering-key-state . Code example from the docs:

from pyglet.window import key

window = pyglet.window.Window()
keys = key.KeyStateHandler()
window.push_handlers(keys)

# Check if the spacebar is currently pressed:
if keys[key.SPACE]:
    pass

If you want to subclass from pyglet.window.Window , this would be a possible approach:

import pyglet
from pyglet.window import key

class MyWindow(pyglet.window.Window):

    def __init__(self):
        super(MyWindow, self).__init__()

        self.key_handler = key.KeyStateHandler()
        self.push_handlers(self.key_handler)

    def on_draw(self):
        self.clear()

    def update(self, _):
        if self.key_handler[key.UP]:
            print('UP key pressed')

if __name__ == '__main__':
    mygame = MyWindow()
    pyglet.clock.schedule_interval(mygame.update, 1/60)
    pyglet.app.run()

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