-
-
Save masaguaro/2669a006b80814cfdd7ab460ea9414d4 to your computer and use it in GitHub Desktop.
A file selection class build for ipywidgets without any extra dependencies.
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 os | |
import ipywidgets as widgets | |
class FileBrowser(object): | |
def __init__(self): | |
self.path = os.getcwd() | |
self._update_files() | |
def _update_files(self): | |
self.files = list() | |
self.dirs = list() | |
if(os.path.isdir(self.path)): | |
for f in os.listdir(self.path): | |
ff = self.path + "/" + f | |
if os.path.isdir(ff): | |
self.dirs.append(f) | |
else: | |
self.files.append(f) | |
def widget(self): | |
box = widgets.VBox() | |
self._update(box) | |
return box | |
def _update(self, box): | |
def on_click(b): | |
if b.description == '..': | |
self.path = os.path.split(self.path)[0] | |
else: | |
self.path = self.path + "/" + b.description | |
self._update_files() | |
self._update(box) | |
buttons = [] | |
if self.files: | |
button = widgets.Button(description='..', background_color='#d0d0ff') | |
button.on_click(on_click) | |
buttons.append(button) | |
for f in self.dirs: | |
button = widgets.Button(description=f, background_color='#d0d0ff') | |
button.on_click(on_click) | |
buttons.append(button) | |
for f in self.files: | |
button = widgets.Button(description=f) | |
button.on_click(on_click) | |
buttons.append(button) | |
box.children = tuple([widgets.HTML("<h2>%s</h2>" % (self.path,))] + buttons) | |
# example usage: | |
# f = FileBrowser() | |
# f.widget() | |
# <interact with widget, select a path> | |
# in a separate cell: | |
# f.path # returns the selected path |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment