Created
November 24, 2018 04:36
-
-
Save elkhadiy/284900b3ea8a13ed7b777ab93a691719 to your computer and use it in GitHub Desktop.
jupyter ipywidget file picker and browser / explorer
This file contains hidden or 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 os | |
import ipywidgets as widgets | |
class FilePicker(object): | |
"""ipywidget for filepicking | |
Display the widget in a notebook: | |
>>> file_picker = FilePicker() | |
>>> file_picker.widget | |
Get the selected file path: | |
>>> file_picker.file | |
""" | |
def __init__(self, rows=20): | |
self.__selected_dir = os.getcwd() | |
self.__item_layout = widgets.Layout(width='auto') | |
self.__nb_rows = rows | |
self.__file_selector = widgets.Select( | |
options=os.listdir(self.__selected_dir), | |
rows=min(len(os.listdir(self.__selected_dir)), self.__nb_rows), | |
layout=self.__item_layout | |
) | |
self.__open_button = widgets.Button( | |
description='open', | |
layout=widgets.Layout(flex='auto 1 auto', width='auto') | |
) | |
self.__parent_button = widgets.Button( | |
icon='chevron-up', | |
layout=widgets.Layout(flex='auto 1 auto', width='auto') | |
) | |
self.__file_selection = widgets.Text( | |
value=os.path.join( | |
self.__selected_dir, self.__file_selector.value), | |
disabled=True, | |
layout=widgets.Layout(flex='1 1 auto', width='auto') | |
) | |
def open_button_clicked(button): | |
if os.path.isdir(self.__file_selection.value): | |
self.__selected_dir = self.__file_selection.value | |
self.__file_selector.options = os.listdir(self.__selected_dir) | |
self.__file_selector.rows = min( | |
len(os.listdir(self.__selected_dir)), self.__nb_rows) | |
def parent_button_clicked(button): | |
self.__selected_dir, _ = os.path.split(self.__selected_dir) | |
self.__file_selector.options = os.listdir(self.__selected_dir) | |
self.__file_selector.rows = min( | |
len(os.listdir(self.__selected_dir)), self.__nb_rows) | |
self.__file_selection.value = os.path.join( | |
self.__selected_dir, self.__file_selector.value | |
) | |
self.file = self.__file_selection.value | |
def update_path(change): | |
self.__file_selection.value = os.path.join( | |
self.__selected_dir, self.__file_selector.value | |
) | |
self.file = self.__file_selection.value | |
self.__parent_button.on_click(parent_button_clicked) | |
self.__open_button.on_click(open_button_clicked) | |
self.__file_selector.observe(update_path) | |
self.widget = widgets.VBox([ | |
widgets.HBox([ | |
self.__parent_button, self.__file_selection, self.__open_button | |
]), | |
self.__file_selector | |
]) | |
self.file = self.__file_selection.value |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment