0

My code:

class MainWindow(Gtk.ApplicationWindow):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.assigned_keys = {
             111:False,
             113:False,
             114:False,
             116:False
        }

        self.set_default_size(600, 250)
        self.set_title("MyApp")

        evk = Gtk.EventControllerKey.new()
        evk.connect("key-pressed", self.key_pressed)
        evk.connect("key-released", self.key_released)
        self.add_controller(evk)

    def key_pressed(self, event, keyval, keycode, state):
        if keycode in self.assigned_keys: self.assigned_keys[keycode] = True

        if (self.assigned_keys[111] and self.assigned_keys[113]):
            print("up + left")
        elif (self.assigned_keys[111] and self.assigned_keys[114]):
            print("up + right")
        elif (self.assigned_keys[116] and self.assigned_keys[113]):
            print("down + left")
        elif (self.assigned_keys[116] and self.assigned_keys[114]):
            print("down + right")
        elif (self.assigned_keys[111]):
            print("up")
        elif (self.assigned_keys[113]):
            print("left")
        elif (self.assigned_keys[114]):
            print("rigth")
        elif (self.assigned_keys[116]):
            print("down")

    def key_released(self, event, keyval, keycode, state):
        if keycode in self.assigned_keys: self.assigned_keys[keycode] = False
    

class MyApp(Adw.Application):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.connect('activate', self.on_activate)

    def on_activate(self, app):
        self.win = MainWindow(application=app)
        self.win.present()

app = MyApp(application_id="com.example.GtkApplication")
app.run(sys.argv)

If press the "up" arrow and then press "left" arrow, the command stops working when you release the left arrow: elif (self.assigned_keys[111]): print("up") It turns out that the previous event - pressing the button stops working.

Is there a way to listen for keys being held down? Maybe some other solution?

I tried adding to the code: event.emit("key-pressed", keyval, keycode, state) but this triggers a single signal instead of a button press

  • Please trim your code to make it easier to find your problem. Follow these guidelines to create a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). – Blue Robin Mar 18 '23 at 21:39

0 Answers0