Getting JS to talk back to Python #3
Replies: 4 comments 9 replies
-
Beta Was this translation helpful? Give feedback.
-
ipywidgetsThis solution works both in browser and VSCode! Unfortunately, it's not what we want. Here, we're making the JS+HTML via ipywidgets. import ipywidgets as widgets
from IPython.display import display
# Python function to be called when the button is clicked
def on_button_click(button):
global data_from_js
data_from_js = text_input.value
print(f"Received data: {data_from_js}")
# Create a text input widget
text_input = widgets.Text(
value='',
placeholder='Enter some text',
description='Text:',
disabled=False
)
# Create a button widget
button = widgets.Button(description="Submit")
button.on_click(on_button_click)
# Display the widgets
display(text_input, button) |
Beta Was this translation helpful? Give feedback.
-
Troubleshooting the Ipython only solution: from IPython.display import display, HTML, Javascript
js_code = """
function sendToPython(){
var data = document.querySelector("#myInput").value;
var kernel = IPython.notebook.kernel;
kernel.execute("data_from_js = '" + data + "'");
}
document.querySelector("#myButton").addEventListener("click", function(){
sendToPython();
});
"""
HTML_code = """
<input type="text" id="myInput" placeholder="Enter some text">
<button id="myButton">Submit</button>
<script type="text/Javascript">{}</script>
""".format(js_code) Different cell (not necessary): display(HTML(HTML_code)) Enter "hello" in input text field, then click "Submit" button. Then, in a different cell: print(data_from_js) |
Beta Was this translation helpful? Give feedback.
-
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
The following are ideas and attempts to use existing tools to have JS "talk back" to Python in a notebook.
That is, communicate some information about events happing on the JS component side back to python variables.
Note: As mentioned in Python-JS two-way communication, we're trying to make this work for browser-based jupyter notebooks (what is launched by
jupyter notebook
in terminal), but also VSCode.Beta Was this translation helpful? Give feedback.
All reactions