Linking keypress in page to a python callback

Hey!

I would like to toggle a panel Toggle widget when I press some keyboard key in the browser tab. Is this possible?

Thanks!

maybe you can define a callback with the keyboard module

Thanks, but that seems unrelated. I need a hook that links the keyboard press in the dashboard tab in the browser.

IIRC bokeh deliberate decided not to include keyboard events in an effort to avoid making it easy to make a keylogger with a bokeh app. I don’t have any major concerns there since any app can be made to do that in end so I’d be happy to expose keyboard events from Panel if you file an issue.

Hi, has this been implemented yet? :slight_smile:

I’ve had a similar need for this, and inspired by another post I made a simple wrapper class for panel objects using reactiveHTML.

import panel as pn
from panel.reactive import ReactiveHTML
import param
pn.extension()

class Enter_watcher(ReactiveHTML):
    value = param.Integer(default=0)
    parameter = param.Parameter()
    
    _template = """
    <div id="wrapper">${parameter}</div>
    """
    
    _dom_events = {'wrapper':['keyup']}
    
    def _wrapper_keyup(self,e):
        try: #Mouse click events seemingly also get passed, but don't follow the same data structure, throwing an exception when trying to grab the 'key' key
            if e.data['key'] == 'Enter':
                self.value+=1
        except:
            pass
        
    def on_click(self, callback):
        return self.param.watch(callback, 'value', onlychanged=False)
    
text_input = pn.widgets.TextInput(name="I react to enter!")
def callback(e):
    print("Enter pressed!")
wrapped = Enter_watcher(parameter=text_input)
wrapped.on_click(callback)
wrapped.servable()

panel_enter_watcher

Note that this only captures the keypress on whatever it is wrapping, not anywhere else on the page.

3 Likes

Are standard events handled in a special way by panel?

I’m referencing to this: ReactiveHTML: data provided to server side event handlers by DOM events
In this example I’ve no useful data in the event.