def __init__(self, address, port=9999): self.address = address self.port = port # Créer un champ de texte (pour ecrire) self.text = widgets.Text(description="Ecrire:", placeholder="Votre commande ici", disabled=True) self.text.on_submit(self.handle_submit) # Créer une zone d'affichage self.output = widgets.HTML(placeholder='Pas de message') # Créer un bouton pour effacer self.clear_button = widgets.Button(description='effacer', disabled=True) self.clear_button.on_click(self.effacer) # Créer un bouton pour quitter self.quit_button = widgets.Button(description='deconnecter', disabled=True) self.quit_button.on_click(self.handle_quit) display(widgets.HBox([self.text, self.clear_button, self.quit_button]), self.output) self.thread = None self.sock = None
def video(core, loop_pause=0.15): # video with button (CV2) live = widgets.Button(description='Live') close = widgets.Button(description='Close') display.display(widgets.HBox([live, close])) def on_live(b): display.clear_output(wait=True) print 'LIVE' core.startContinuousSequenceAcquisition(1000) # time overridden by exposure time.sleep(.2) cv2.namedWindow('Video', cv2.WINDOW_NORMAL) cv2.setWindowProperty('Video', cv2.WND_PROP_ASPECT_RATIO, cv2.WINDOW_KEEPRATIO) cv2.resizeWindow('Video', 500, 500) img = np.zeros((500, 500)) print 'To stop, click window + press ESC' while 1: time.sleep(loop_pause) if core.getRemainingImageCount() > 0: img = core.getLastImage() cv2.imshow('Video', img) k = cv2.waitKey(30) if k == 27: # ESC key; may need 255 mask? break print 'STOPPED' core.stopSequenceAcquisition() def on_close(b): if core.isSequenceRunning(): core.stopSequenceAcquisition() cv2.destroyWindow('Video') live.on_click(on_live) close.on_click(on_close)
def __init__(self, system=None, working_dir='', next_function=None, multiple_flag=False): if working_dir == '': if system is None: working_dir = './' else: working_dir = system.System.get_working_dir() super(SelectFolderWithDefaultPaths, self).__init__(working_dir=working_dir, next_function=next_function, multiple_flag=multiple_flag) ipts = os.path.basename(self.working_dir) button_layout = widgets.Layout(width='30%', border='1px solid gray') hbox = widgets.HBox([widgets.Button(description="Jump to {} Shared Folder".format(ipts), button_style='success', layout=button_layout), widgets.Button(description="Jump to My Home Folder", button_style='success', layout=button_layout)]) go_to_shared_button_ui = hbox.children[0] go_to_home_button_ui = hbox.children[1] go_to_shared_button_ui.on_click(self.display_file_selector_from_shared) go_to_home_button_ui.on_click(self.display_file_selector_from_home) display(hbox) self.display_file_selector()
def snap(core, mode='mpl'): def on_snap_mpl(b): core.snapImage() img = core.getImage() plt.imshow(img, cmap='gray') plt.show() def on_snap_cv2(b): cv2.destroyWindow('Snap') cv2.namedWindow('Snap', cv2.WINDOW_NORMAL) cv2.resizeWindow('Snap', 500, 500) cv2.setWindowProperty('Snap', cv2.WND_PROP_ASPECT_RATIO, cv2.WINDOW_KEEPRATIO) core.snapImage() time.sleep(.1) img = core.getImage() cv2.imshow('Snap', img) k = cv2.waitKey(30) def on_close_cv2(b): cv2.destroyWindow('Snap') snap = widgets.Button(description='Snap') if mode == 'cv2': snap.on_click(on_snap_cv2) close = widgets.Button(description='Close') close.on_click(on_close_cv2) display.display(widgets.HBox([snap, close])) else: # mode=='mpl' snap.on_click(on_snap_mpl) display.display(snap)
def __init__(self, iterable, func, fig): self._iterable = iterable self.func = func self.fig = fig self.axes = np.array(self.fig.axes).flatten() self.idx = 0 self.btn_first = widgets.Button(description='First') self.btn_prev = widgets.Button(description='Prev') self.int_box = widgets.BoundedIntText(value=0, min=0, max=len(iterable) - 1) self.btn_next = widgets.Button(description='Next') self.btn_last = widgets.Button(description='Last') self.btn_random = widgets.Button(description='Random') self.int_box.observe(self.handle_int_box, names='value') self.btn_first.on_click(self.on_first) self.btn_prev.on_click(self.on_prev) self.btn_next.on_click(self.on_next) self.btn_last.on_click(self.on_last) self.btn_random.on_click(self.on_random) btn_hbox = widgets.HBox() btn_hbox.children = [ self.btn_first, self.btn_prev, self.int_box, self.btn_next, self.btn_last, self.btn_random ] self.update_graph() display(btn_hbox)
def float_range_controller(tmin, tmax, start_value=None): if start_value is None: start_value = [tmin, min(tmin + 50, tmax)] slider = widgets.FloatRangeSlider( value=start_value, min=tmin, max=tmax, step=0.1, description='time window', continuous_update=False, orientation='horizontal', readout=True, readout_format='.1f', layout=Layout(width='90%')) forward_button = widgets.Button(description='▶', layout=Layout(width='50px')) forward_button.on_click(lambda b: move_range_slider_up(slider)) backwards_button = widgets.Button(description='◀', layout=Layout(width='50px')) backwards_button.on_click(lambda b: move_range_slider_down(slider)) button_box = widgets.HBox(children=[backwards_button, forward_button]) button_box.layout.align_items = 'center' controller = widgets.VBox( layout=Layout(width='250px'), children=[slider, button_box]) return controller
def __init__(self, options=None, is_lower_better=True, **kwargs): self.is_desc = is_lower_better self.options = None self.curr_option = None self.sort = widgets.Button(icon=self.sort_icon, disabled=True, layout=widgets.Layout(**BUTTON_LAYOUT)) self.prev = widgets.Button(icon="angle-left", disabled=True, layout=widgets.Layout(**BUTTON_LAYOUT)) self.drop = widgets.Dropdown(layout=widgets.Layout(**TEXT_LAYOUT)) self.next = widgets.Button(icon="angle-right", disabled=True, layout=widgets.Layout(**BUTTON_LAYOUT)) # Handler definition self.sort.on_click(self.reverse_options) self.prev.on_click(self.prev_option) self.drop.observe(self.select_option, names="value") self.next.on_click(self.next_option) super().__init__(**kwargs) if options is not None: self.update_state(0, options)
def jspecgram(snd, nt=1000, starttime=None, endtime=None, nperseg=512, freqsmoothing=1, cmap='viridis', dynrange=(-90., -40.), maxfreq=10e3): nfft = int(nperseg*freqsmoothing) d = sndplot.Spectrogram(snd, nt=nt, starttime=starttime, endtime=endtime, nperseg=nperseg, nfft=nfft, cmap=cmap, dynrange=dynrange, maxfreq=maxfreq) button_play = widgets.Button(description='play') button_play.on_click(d.play) button_stop = widgets.Button(description='stop') button_stop.on_click(d.stop_playing) display(widgets.HBox((button_play, button_stop))) drs = widgets.FloatRangeSlider(value=(-75, -35), min=-120, max=0, step=1, description='dynamic range (dB)') drs.observe(lambda change: d.set_clim(change['new']), names='value') display(drs) freqs = widgets.FloatRangeSlider(value=(0, 10), min=0, max=snd.fs/2e3, step=0.1, description='frequency range (kHz)') freqs.observe(lambda change: d.set_freqrange(change['new']), names='value') display(freqs) npersegw = widgets.IntText(value=nperseg, min=1, max=4096 * 2, description='nperseg') npersegw.observe(lambda change: d.set_nperseg(change['new']), names='value') display(npersegw) return d
def show(self): F_list = [] for n, f in enumerate(self.filters): tab_list = [] for name, w in sorted(getattr(f, 'widgets', {}).items()): tab_list.append(w) F_list.append(widgets.VBox(tab_list)) tab = widgets.Accordion(children=F_list) for n, f in enumerate(self.filters): tab.set_title(n, '[+] ' + f.name) display(tab) btn = self.get_or_create( 'btn', lambda x: widgets.Button(description='Refresh & Draw')) btn.on_click(self.redrawfig) display(btn) btn_dupfig = self.get_or_create( 'btn_dupfig', lambda x: widgets.Button(description='+')) btn_dupfig.on_click(self.new_view) display(btn_dupfig) wdg_isholdon = self.get_or_create( 'wdg_isholdon', lambda x: widgets.Checkbox(description='Hold on', value=False)) display(wdg_isholdon) plt = self.get_or_create('plt', lambda x: MPL_Plotter(self.filters[-1]))
def plot_board(self): clear_output() options = self._board_state['words'] options.sort() spy_selector = widgets.Dropdown(options=options, description='Select Target', disabled=False, value=None) display(spy_selector) spy_selector.observe(self._selection_change) kill_button = widgets.Button(description='Eliminate') output = widgets.Output() display(kill_button, output) kill_button.on_click(self._kill_button_clicked) fig, ax = plt.subplots(figsize=(8, 6)) ax.axis('tight') ax.axis('off') table = ax.table(cellText=self._board, loc='center', cellLoc='center', cellColours=self._get_board_colors()) table.set_fontsize(14) table.scale(1.5, 3.5) plt.show() et_button = widgets.Button(description='End Turn') output = widgets.Output() display(et_button, output) et_button.on_click(self._et_button_clicked)
def __init__(self, disambiguation_map, start = 0): self.map = disambiguation_map.copy() #Note, deep copy to make sure this is separate self.todo = sorted([v for k,v in self.map.items()], key = lambda x: x[0]) self.position = start self.toDisambiguate = widgets.Label(value = self.todo[self.position][0]) self.disambiguated = widgets.Text(value=self.todo[self.position][0], placeholder='Type something', description='Root:', disabled=False) self.next = widgets.Button(description = 'Next') self.next.on_click(self.next_clicked) self.none = widgets.Button(description = 'None') self.none.on_click(self.none_clicked) self.previous = widgets.Button(description = 'Previous') self.previous.on_click(self.previous_clicked) bottom_rule = widgets.HBox([self.disambiguated,self.next,self.none,self.previous]) bottom_rule.layout.justify_content = 'space-between' self.tool = widgets.VBox([self.toDisambiguate,bottom_rule]) self.tool.layout.justify_content = 'space-around'
def make_course_ids_input(): """ Make box and buttons for course id entry. On submit button click, class ids updates with the value in the text box """ t = widgets.Text(description='Class id') submit = widgets.Button(description='Add id', button_style='success') reset = widgets.Button(description='Reset ids') out = widgets.Output(layout={'border': '1px solid black'}) def handle_add(change): InteractiveConfiguration.add_course_id(t.value) # Clear the box t.value = '' show_class_ids() def handle_reset(change): InteractiveConfiguration.reset_course_ids() show_class_ids() def show_class_ids(): out.clear_output() with out: print(' ----Canvas class ids---- ') for cid in InteractiveConfiguration.course_ids: print(cid) submit.on_click(handle_add) reset.on_click(handle_reset) button_box = widgets.HBox([reset, submit]) input_box = widgets.VBox([t, button_box]) display(widgets.HBox([input_box, out]))
def __init__(self, min=0, max=1, step=0.1, description="MultiRange", disabled=False): self.min = min self.max = max self.step = step self.description = description self.disabled = disabled self.range_slider_list = [] self.add_range_button = widgets.Button(description="Add range") self.add_range_button.on_click(self.handle_add_range_event) self.rm_range_button = widgets.Button(description="Rm range") self.rm_range_button.on_click(self.handle_rm_range_event) # combined range over all sliders, excluding possible overlaps self.selected_values = [] # Vertical box for displaying all the sliders self.vbox = widgets.VBox() # create a first slider and update vbox children for displaying self.handle_add_range_event() # callback function to be called when the widgets value changes # this needs to accept the usual 'change' dict as in other widgets self.observe_callback = None
def get_delete_files_widget(self): """Create delete files widget""" files_list = self.get_delete_files_list() questions = self.get_delete_questions() files_questions_box = widgets.VBox([files_list, questions], layout=LAYOUT_DELETE_QUESTION_BOX) delete_submit_button = widgets.Button(description='Delete', style=STYLE_BUTTON, button_style='primary', layout=LAYOUT_DELETE_BUTTON) delete_submit_button.on_click(self.action_submit) self.delete_text_field = widgets.Text(layout=LAYOUT_DELETE_TEXTFIELD) delete_submit_box = widgets.HBox( [self.delete_text_field, delete_submit_button], layout=LAYOUT_DELETE_SUBMIT_BOX) button_goback = widgets.Button(description='Go Back', style=STYLE_BUTTON, button_style='warning', layout=LAYOUT_GOBACK_BUTTON) button_goback.on_click(self.action_goback) goback_box = widgets.HBox([button_goback], layout=LAYOUT_GOBACK_BOX) return widgets.VBox( [files_questions_box, delete_submit_box, goback_box])
def count_steps(self, *args): if self.has_time: treffer_links = 0 treffer_rechts = 0 for i in range(0, len(self.table_rows)): if self.table_rows[i][2].value == True: treffer_links += 1 if self.table_rows[i][3].value == True: treffer_rechts += 1 if treffer_links >= self.textform.meas_step_count["links"]: style_name_links = 'success' elif treffer_links < self.textform.meas_step_count["links"]: style_name_links = 'danger' if treffer_rechts >= self.textform.meas_step_count["rechts"]: style_name_rechts = 'success' elif treffer_rechts < self.textform.meas_step_count["rechts"]: style_name_rechts = 'danger' StepCount = widgets.HBox([ widgets.Button(description="Linke Schritte: " + str(treffer_links), button_style=style_name_links), widgets.Button(description="Rechte Schritte: " + str(treffer_rechts), button_style=style_name_rechts)]) self.stepcount = StepCount display(self.stepcount) return StepCount
def __bottom_panel(self): list_ui = [] if self.prev_button: self.prev_button_ui = widgets.Button( description="<< Previous Step", tooltip='Click to move to previous step', button_style='success', disabled=False, layout=widgets.Layout(width='20%')) self.prev_button_ui.on_click(self.prev_button_clicked) list_ui.append(self.prev_button_ui) self.current_state_label_ui = widgets.Label( " ", layout=widgets.Layout(width='70%')) list_ui.append(self.current_state_label_ui) if self.next_button: self.next_button_ui = widgets.Button( description="Next Step>>", tooltip='Click to move to next step', button_style='warning', disabled=True, layout=widgets.Layout(width='20%')) list_ui.append(self.next_button_ui) self.next_button_ui.on_click(self.next_button_clicked) self.bottom_panel = widgets.HBox(list_ui)
def int_range_controller(max, min=0, start_range=(0, 30), description='units', orientation='horizontal', continuous_update=False): slider = widgets.IntRangeSlider( value=start_range, min=min, max=max, description=description, continuous_update=continuous_update, orientation=orientation, readout=True, style={'description_width': 'initial'}, layout=Layout(width='100%')) up_button = widgets.Button(description='▲', layout=Layout(width='100%')) up_button.on_click(lambda b: move_range_slider_up(slider)) down_button = widgets.Button(description='▼', layout=Layout(width='100%')) down_button.on_click(lambda b: move_range_slider_down(slider)) controller = widgets.VBox( layout=Layout(width='175px'), children=[ slider, widgets.VBox(children=[up_button, down_button])]) return controller
def __init__(self, text, solution, *other_correct_choices, is_correct_fun=None, inst=None): self.correct_choices = list(other_correct_choices) self.correct_choices.append(solution) self.is_correct_fun = is_correct_fun textbox = widgets.HTML(value='<h4 style="font-size:14px;">{}</h4>'.format(text)) instbox = widgets.HTML(value='<i>{}</i>'.format(inst)) answer_input = widgets.Text() submit_button = widgets.Button(description="OK") give_up_button = widgets.Button(description="Lösung zeigen") button_box = widgets.HBox(children=[submit_button, give_up_button]) super().__init__(children=[textbox,instbox, answer_input, button_box]) self.answered = False def on_ok_button_clicked(b): if self.answered: return given_answer = answer_input.value answer_input.layout.border = '2px solid lightgreen' if self.is_correct(given_answer) else '2px solid red' submit_button.on_click(on_ok_button_clicked) def on_show_solution_button_clicked(b): answer_input.value = solution answer_input.layout.border = '2px solid lightgreen' answer_input.disabled = True give_up_button.on_click(on_show_solution_button_clicked)
def make_time_window_controller(tmin, tmax, start=0, duration=5.): slider = widgets.FloatSlider( value=start, min=tmin, max=tmax, step=0.1, description='window start (s):', continuous_update=False, orientation='horizontal', readout=True, readout_format='.1f') duration_widget = widgets.BoundedFloatText( value=duration, min=0, max=tmax - tmin, step=0.1, description='duration (s):', ) forward_button = widgets.Button(description='▶') forward_button.on_click(lambda b: move_slider_up(slider, duration_widget.get_interact_value())) backwards_button = widgets.Button(description='◀') backwards_button.on_click(lambda b: move_slider_down(slider, duration_widget.get_interact_value())) controller = widgets.VBox( children=[ widgets.VBox(children=[slider, duration_widget]), widgets.HBox(children=[backwards_button, forward_button])]) return controller
def select_export_folder(self, ipts_folder='./'): def display_file_selector_from_shared(ev): start_dir = os.path.join(ipts_folder, 'shared') self.output_folder_ui.remove() self.display_file_selector(start_dir=start_dir) def display_file_selector_from_home(ev): import getpass _user = getpass.getuser() start_dir = os.path.join('/SNS/users', _user) self.output_folder_ui.remove() self.display_file_selector(start_dir=start_dir) ipts = os.path.basename(self.working_dir) button_layout = widgets.Layout(width='30%', border='1px solid gray') hbox = widgets.HBox([ widgets.Button(description="Jump to {} Shared Folder".format(ipts), button_style='success', layout=button_layout), widgets.Button(description="Jump to My Home Folder", button_style='success', layout=button_layout) ]) go_to_shared_button_ui = hbox.children[0] go_to_home_button_ui = hbox.children[1] go_to_shared_button_ui.on_click(display_file_selector_from_shared) go_to_home_button_ui.on_click(display_file_selector_from_home) display(hbox) self.display_file_selector()
def __init__(self, *args): """ Initialization of step counting box. """ treffer_links = 0 treffer_rechts = 0 for i in range(0,len(args[0].shoeOF.table_rows)): if args[0].shoeOF.table_rows[i][2].value == True: treffer_links += 1 if args[0].shoeOF.table_rows[i][3].value == True: treffer_rechts += 1 if treffer_links >= args[1].meas_step_count["links"]: style_name_links = 'lightgreen' elif treffer_links < args[1].meas_step_count["links"]: style_name_links = 'danger' if treffer_rechts >= args[1].meas_step_count["rechts"]: style_name_rechts = 'lightgreen' elif treffer_rechts < args[1].meas_step_count["rechts"]: style_name_rechts = 'danger' self.StepCount = widgets.HBox([ widgets.Button(description="Linke Schritte: " + str(treffer_links), button_style=style_name_links), widgets.Button(description="Rechte Schritte: " + str(treffer_rechts), button_style=style_name_rechts)])
def create_textinputquiz_widget(description, text_description, correct_answer, a2, hint): ##grid for option table correct_answer = correct_answer ##float ##str alternativ = widgets.Text(value='', placeholder='', description='', disabled=False, layout=(Layout(width='auto')) ) ##question description description_out = widgets.Output(layout=Layout(width='auto')) with description_out: print(description) ##description before text widget text_description_out = widgets.Output(layout=Layout(width='auto')) with text_description_out: print(text_description) ##description after text widget e.g. units a2_out = widgets.Output(layout=Layout(width='auto')) with a2_out: print(a2) ## feedback_out = widgets.Output() def check_selection(b): a = alternativ.value if a == correct_answer: s = "You are right! The first level 2 magic word is 'JOHN'" else: s = "It seems like you got the wrong result. Check the hint!" with feedback_out: feedback_out.clear_output() print(s) return check = widgets.Button(description="check") check.on_click(check_selection) ## hint_out = widgets.Output() def hint_selection(b): with hint_out: print(hint) with feedback_out: feedback_out.clear_output() print(hint) hintbutton = widgets.Button(description="hint") hintbutton.on_click(hint_selection) return widgets.VBox([description_out, widgets.HBox([text_description_out, alternativ, a2_out]), widgets.HBox([hintbutton, check]), feedback_out], layout=Layout(display='flex', flex_flow='column', align_items='stretch', width='auto'))
def interactive_selection(): from ipywidgets import Button, HBox, VBox, widgets, Layout, GridspecLayout from IPython.display import display ## Generate interactive grid d={} output = widgets.Output #output.clear_output global hold_selection hold_selection = [] #generate hold_key_matrix hold_key_matrix = generate_hold_key_matrix() def on_button_clicked(b): b.style.button_color = 'lightgreen' global hold_selection hold_selection.append(b.description) ##define grid for R in range(hold_key_matrix.shape[0]): hold = hold_key_matrix[R,:].tolist() #convert to list, start with "18" item = [Button(description=h) for h in hold] #list of buttons d['{}{}'.format('H_box',R)] = HBox(item) #store all Hboxes in dictionary #define buttons for C in range(hold_key_matrix.shape[1]): button = item[C] # button.on_click(on_button_clicked) whole_grid = VBox([d['H_box0'], d['H_box1'], d['H_box2'], d['H_box3'], d['H_box4'], d['H_box5'], d['H_box6'], d['H_box7'], d['H_box8'], d['H_box9'], d['H_box10'], d['H_box11'], d['H_box12'], d['H_box13'], d['H_box14'], d['H_box15'], d['H_box16'], d['H_box17']]) grid = GridspecLayout(18,11) grid[:,:] = whole_grid display(grid) #display(whole_grid) ## generate Termination buttons # predict grade button function def end_button_clicked(b): predict_grade_JF(hold_selection) #define reload_button.on_clicked def reload_on_clicked(b): global hold_selection for H in hold_selection: index_nd_array = np.where(hold_key_matrix==H) whole_grid.children[int(index_nd_array[0])].children[int(index_nd_array[1])].style.button_color = None hold_selection=[] ##display reload and predict grade button end_button = widgets.Button(description='Predict difficulty!', button_style='danger') end_button.on_click(end_button_clicked) reload_button = widgets.Button(description='Reload', button_style='primary') reload_button.on_click(reload_on_clicked) final_buttons = HBox([end_button, reload_button]) display(final_buttons)
def __create_vote_buttons__(self): button_yes = widgets.Button(description='Yes') button_no = widgets.Button(description='No') button_skip = widgets.Button(description='Skip') button_back = widgets.Button(description='Back') button_reset = widgets.Button(description='Clear All') self.buttons = HBox([button_yes, button_no, button_skip, button_back, button_reset])
def createSubsetsPanel(self): self.subsetsui = widgets.SelectMultiple( options=[sset.label for sset in self.gluemanager.data.subsets], value=[], rows=4, disabled=False ) self.subsetsui.layout = widgets.Layout(width='99%') bt = widgets.Button( description='Create new Subset.', disabled=False, button_style='', # 'success', 'info', 'warning', 'danger' or '' tooltip='createa new subset from current selection', ) bt.layout = widgets.Layout(width='99%') tx = widgets.Text( value='', placeholder='new subset name', disabled=False ) tx.layout = widgets.Layout(width='99%') bt.on_click(lambda e : GlueManagerWidget.createSubsetFromSelection(self, tx)) dl = widgets.Button( description='remove selected Subsets', disabled=False, button_style='danger', tooltip='Removes active subsets from the data workspace', ) dl.layout = widgets.Layout(width='99%') dl.on_click(lambda e : GlueManagerWidget.deleteSubsetFromSelection(self)) sl = widgets.Button( description='Hide selected subsets', disabled=False, button_style='warning', tooltip='', ) sl.layout = widgets.Layout(width='99%') vb = widgets.VBox([dl, sl]) vb2 = widgets.VBox([tx, bt]) hb1 = widgets.HBox([vb2,self.subsetsui,vb]) vb3 = widgets.VBox([hb1]) return vb3
def __init__(self, iterable, button_names, apply_function, button_layout=None): """ Iterate an iterable, apply a function at each step and collect button clicked for a collection of buttons. :param iterable: e.g., pandas dataframe, list, etc. :param buttons_name: list of strings, showing the display-name (and content) of the shown buttons :param apply_function: function to apply at each step Example of usage (to annotate if 10 numbers are even or odd manually): bti = ButtonIterator(range(10), button_names=['odd', 'even'], apply_function=lambda x: print(x)) bti.start() print(bti.results) """ self.iterable = iterable self.is_pandas = False if isinstance(self.iterable, pd.Series) or isinstance( self.iterable, pd.DataFrame): self.is_pandas = True # use it to take next element via .iloc() self.results = [] # store the results as you proceed self.apply_function = apply_function # Create progress bar self.progress_bar = IntProgress(min=0, max=len(self.iterable), value=1) self.progress_bar.bar_style = 'info' self.interface_container = [self.progress_bar] if button_layout is None: self.button_layout = widgets.Layout(width='30%', height='40px') # Create the buttons and assign actions for button_name in button_names: # Create the button button = widgets.Button(description=button_name, layout=self.button_layout) # Assign action method on each button button.on_click(self.log_selected_button) self.interface_container.append(button) # Create extra a "back" & "next" buttons to change the iterators position manually back_button = widgets.Button(description='|Back|', layout=self.button_layout) next_button = widgets.Button(description='|Next|', layout=self.button_layout) back_button.on_click(self._back_action) next_button.on_click(self._next_action) self.interface_container.extend([back_button, next_button]) # Create the GUI interface self.interface = widgets.VBox(self.interface_container) # Current index in the iterator self.current_index = 0
def create_multipleChoice_widget(description, options, correct_answer, hint): if correct_answer not in options: options.append(correct_answer) correct_answer_index = options.index(correct_answer) radio_options = [(words, i) for i, words in enumerate(options)] alternativ = widgets.RadioButtons( options = radio_options, description = '', disabled = False, indent = False, align = 'center', ) description_out = widgets.Output(layout=Layout(width='auto')) with description_out: print(description) feedback_out = widgets.Output() def check_selection(b): a = int(alternativ.value) if a==correct_answer_index: s = '\x1b[6;30;42m' + "correct" + '\x1b[0m' +"\n" else: s = '\x1b[5;30;41m' + "try again" + '\x1b[0m' +"\n" with feedback_out: feedback_out.clear_output() print(s) return check = widgets.Button(description="check") check.on_click(check_selection) hint_out = widgets.Output() def hint_selection(b): with hint_out: print(hint) with feedback_out: feedback_out.clear_output() print(hint) hintbutton = widgets.Button(description="hint") hintbutton.on_click(hint_selection) return widgets.VBox([description_out, alternativ, widgets.HBox([hintbutton, check]), feedback_out], layout=Layout(display='flex', flex_flow='column', align_items='stretch', width='auto'))
def __init__(self, text, correctChoice, *wrongChoices, sonst=False, inst=single): choices = list(wrongChoices) choices.append(correctChoice) choices.sort() buttons = [ widgets.Button(description=choice, layout=widgets.Layout(width="250px")) for choice in choices ] if sonst: buttons.append( widgets.Button(description="Keine der anderen Möglichkeiten", layout=widgets.Layout(width="250px"))) def on_button_clicked(b): choice = b.description if b.style.button_color == 'lightgreen' or b.style.button_color == 'red': b.style.button_color = None else: b.style.button_color = 'lightgreen' if choice == self.correct else 'red' if self.answered: #b.style.button_color = None #self.answered = False return self.answered = True # textbox.layout.border = "2px solid lightgreen" if choice == self.correct else "2px solid red" for button in buttons: button.on_click(on_button_clicked) allbox = [] while not buttons == []: if len(buttons) > 2: allbox.append(widgets.HBox(children=[buttons[0], buttons[1]])) buttons.pop(0) buttons.pop(0) else: allbox.append(widgets.HBox(children=buttons)) break textbox = widgets.HTML( value='<h4 style="font-size:14px;">{}</h4>'.format(text), layout=widgets.Layout(justify_content="center")) instbox = widgets.HTML(value='<i>{}</i>'.format(inst), layout=widgets.Layout(justify_content="center")) super().__init__(children=[textbox, instbox] + allbox) self.correct = correctChoice self.answered = False
def reset(self): self._input_grids = [] self._wrappers_input_grids = [] self._obj_store = {} self._value_traces = {} self._value_trackers = {} self._interactions = [] self._constants = [] for i, obj in enumerate(self.inputs): grid_id = f"I{i}" value_trackers, value_traces = self._get_value_trackers_and_traces( obj, grid_id) self._value_traces.update(value_traces) self._value_trackers.update(value_trackers) self._input_grids.append( InputGridWidget(session=self, grid_id=grid_id, df=obj, value_trackers=value_trackers)) self._wrappers_input_grids.append( ShowHideWidget(f"Input {i + 1}", self._input_grids[-1].get_widget())) self._output_grid = OutputGridWidget(grid_id="O", session=self) self._scratch_grid = ScratchGridWidget(grid_id="S", session=self) self._synthesis_output_widget = SynthesisOutputWidget( session=self, allow_composition=self._allow_composition) self._wrapper_output_grid = ShowHideWidget( 'Partial Output', self._output_grid.get_widget()) self._wrapper_scratch_grid = ShowHideWidget( 'Scratch', self._scratch_grid.get_widget()) self._synthesize_button = widgets.Button(description='Synthesize') self._synthesize_button.button_style = 'success' self._synthesize_output = widgets.Output() self._synthesize_solution_output = widgets.Output() self._synthesize_button.on_click(self._onclick_synthesize) self._output_reset_button = widgets.Button(description="Reset") self._output_reset_button.on_click(self._reset_output) self._output_reset_button.button_style = 'info' for i, obj in enumerate(self.inputs): self._obj_store[f"I{i}"] = obj self._explanation_widget = widgets.Text( description=r'\(f\)', disabled=True, style={'description_width': '9px'}, )
def create_textinputquiz_widget(description, text_description, correct_answer, a2, hint): ##grid for option table correct_answer = correct_answer ##float ##str alternativ = widgets.Text(value = '', placeholder = '', description = '', disabled = False, layout=(Layout(width = 'auto')) ) ##question description description_out = widgets.Output(layout=Layout(width='auto')) with description_out: print(description) ##description before text widget text_description_out = widgets.Output(layout=Layout(width='auto')) with text_description_out: print (text_description) ##description after text widget e.g. units a2_out = widgets.Output(layout=Layout(width='auto')) with a2_out: print(a2) ## feedback_out = widgets.Output() def check_selection(b): a = alternativ.value if a==correct_answer: s = '\x1b[6;30;42m' + "correct" + '\x1b[0m' +"\n" #green color else: s = '\x1b[5;30;41m' + "try again" + '\x1b[0m' +"\n" #red color with feedback_out: feedback_out.clear_output() print(s) return check = widgets.Button(description="check") check.on_click(check_selection) ## hint_out = widgets.Output() def hint_selection(b): with hint_out: print(hint) with feedback_out: feedback_out.clear_output() print(hint) hintbutton = widgets.Button(description="hint") hintbutton.on_click(hint_selection) return widgets.VBox([description_out, widgets.HBox([text_description_out, alternativ, a2_out]), widgets.HBox([hintbutton, check]), feedback_out], layout=Layout(display='flex', flex_flow='column', align_items='stretch', width='auto'))