from __future__ import print_function # For py 2.7 compat
from IPython.html import widgets # Widget definitions
from IPython.display import display # Used to display widgets in the notebook
from IPython.utils.traitlets import Unicode # Used to declare attributes of our widget
class TestWidget(widgets.DOMWidget):
_view_name = Unicode('TestView', sync=True)
def __init__(self, **kwargs):
super(TestWidget, self).__init__(**kwargs)
self.on_msg(self._handle_button_msg)
def _handle_button_msg(self, _, content):
if content.get('event', '') == 'click':
self.on_click(content)
elif content.get('event', '') == 'keypress':
self.on_key_press(content)
def on_click(self, content):
print("Button {b}".format(b=content['button']))
def on_key_press(self, content):
print("Key {c}".format(c=content['code']))
%%javascript
require(["widgets/js/widget"], function(WidgetManager){
var TestView = IPython.DOMWidgetView.extend({
render: function(){
this.$canvas = $('<canvas />')
.attr('width', '200')
.attr('height', '100')
.attr('style', 'background: black;')
.attr('tabindex', '1')
.appendTo(this.$el);
},
events: {
'keydown': 'keypress',
'click': 'click',
},
keypress: function(e) {
var code = e.keyCode || e.which;
this.send({event: 'keypress', code: code});
},
click: function(e) {
this.send({event: 'click', button: e.button});
}
});
WidgetManager.register_widget_view('TestView', TestView);
});
my_widget = TestWidget()
display(my_widget)