diff --git a/main.py b/main.py index e1b7cdb93..3b35d5f37 100755 --- a/main.py +++ b/main.py @@ -410,5 +410,6 @@ def handle_keys(e): keyboard = ui.keyboard(handle_keys) ui.label('Key events can be caught globally by using the keyboard element.') + ui.checkbox('Track key events').bind_value_to(keyboard.view, 'active') ui.run(port=8080) diff --git a/nicegui/elements/keyboard.py b/nicegui/elements/keyboard.py index 68e026d57..1103467c8 100644 --- a/nicegui/elements/keyboard.py +++ b/nicegui/elements/keyboard.py @@ -7,22 +7,28 @@ class KeyboardView(CustomView): - def __init__(self, handle_keys: Callable): + def __init__(self, handle_keys: Callable, active: bool = True): super().__init__('keyboard', __file__, activeJSEvents=['keydown', 'keyup', 'keypress']) self.allowed_events = ['keyboardEvent'] self.style = 'display: none' - self.initialize(temp=False, on_keyboardEvent=handle_exceptions(provide_arguments(handle_keys, 'key_data', 'event_type'))) + self.active = active + + def execute_when_active(*args): + if self.active: + handle_exceptions(provide_arguments(handle_keys, 'key_data', 'event_type'))(*args) + + self.initialize(temp=False, on_keyboardEvent=execute_when_active) class Keyboard(Element): - def __init__(self, handle_keys: Callable = None): + def __init__(self, handle_keys: Callable = None, active: bool = True): """ Keyboard Adds global keyboard event tracking. :param handle_keys: callback to be executed when keyboard events occur. + :param active: boolean flag indicating whether the callback should be executed or not """ - - super().__init__(KeyboardView(handle_keys=handle_keys)) + super().__init__(KeyboardView(handle_keys=handle_keys, active=active))