Skip to content

Instantly share code, notes, and snippets.

@brunomsantiago
Last active December 1, 2023 11:29
Show Gist options
  • Save brunomsantiago/e0ab366fc0dbc092c1a5946b30caa9a0 to your computer and use it in GitHub Desktop.
Save brunomsantiago/e0ab366fc0dbc092c1a5946b30caa9a0 to your computer and use it in GitHub Desktop.
Streamlit keyboard shortcuts to buttons (tested on streamlit 1.4.0)
import streamlit as st
import streamlit.components.v1 as components
def left_callback():
st.write('Left button was clicked')
def right_callback():
st.write('Right button was clicked')
left_col, right_col, _ = st.columns([1, 1, 3])
with left_col:
st.button('LEFT', on_click=left_callback)
with right_col:
st.button('RIGHT', on_click=right_callback)
components.html(
"""
<script>
const doc = window.parent.document;
buttons = Array.from(doc.querySelectorAll('button[kind=primary]'));
const left_button = buttons.find(el => el.innerText === 'LEFT');
const right_button = buttons.find(el => el.innerText === 'RIGHT');
doc.addEventListener('keydown', function(e) {
switch (e.keyCode) {
case 37: // (37 = left arrow)
left_button.click();
break;
case 39: // (39 = right arrow)
right_button.click();
break;
}
});
</script>
""",
height=0,
width=0,
)
@CharlyWargnier
Copy link

Great script!

@aghasemi
Copy link

aghasemi commented Feb 8, 2022

The window parent trick is great. Can one use this idea to load and use third-party javascript libraries?

@brunomsantiago
Copy link
Author

I don't know much javascript. I've just evolved a snippet posted on a streamlit issue
streamlit/streamlit#1291

@aghasemi
Copy link

aghasemi commented Feb 9, 2022

Managed to solve it. Will post the "trick" here. Again thanks a lot for your and their window.parent idea. That's the key!

@aghasemi
Copy link

aghasemi commented Feb 9, 2022

@IsakAlmgren
Copy link

Hi!
This doesn't work out of the box anymore, I suspect Streamlit has changed something in how buttons are generated.

Here's the fix: (As of today, at least…)
Replace
buttons = Array.from(doc.querySelectorAll('button[kind=primary]'));
with
buttons = Array.from(doc.querySelectorAll('button'));

@brunomsantiago
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment