Last active
December 1, 2023 11:29
-
-
Save brunomsantiago/e0ab366fc0dbc092c1a5946b30caa9a0 to your computer and use it in GitHub Desktop.
Streamlit keyboard shortcuts to buttons (tested on streamlit 1.4.0)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, | |
) |
The window parent trick is great. Can one use this idea to load and use third-party javascript libraries?
I don't know much javascript. I've just evolved a snippet posted on a streamlit issue
streamlit/streamlit#1291
Managed to solve it. Will post the "trick" here. Again thanks a lot for your and their window.parent
idea. That's the key!
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'));
There is a lib now: https://github.com/adriangalilea/streamlit-shortcuts
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Great script!