Skip to content

Instantly share code, notes, and snippets.

@diramazioni
Forked from DrDub/selectfile.py
Created September 23, 2019 17:25
Show Gist options
  • Save diramazioni/c0f53832dc2dfa9bc6bff8d33a6cf9b5 to your computer and use it in GitHub Desktop.
Save diramazioni/c0f53832dc2dfa9bc6bff8d33a6cf9b5 to your computer and use it in GitHub Desktop.
A file selection class build for ipywidgets without any extra dependencies.
import os
import ipywidgets as widgets
class FileBrowser(object):
def __init__(self, init_path=None):
if init_path:
self.path = os.getcwd()+'/'+init_path
else:
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)
self.dirs = sorted(self.dirs)
self.files = sorted(self.files)
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 = []
imgs = []
if self.files:
button = widgets.Button(description='..')
button.on_click(on_click)
button.style.button_color = 'lightgreen'
buttons.append(button)
for f in self.dirs:
button = widgets.Button(description=f, background_color='#ddffff')
if 'img' in f:
button.style.button_color = 'lightblue'
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)
if self.files:
box.children = tuple([widgets.HTML("<h2>%s</h2>" % (self.path,))] + buttons)
else:
if any(c in self.path for c in ['.png', '.gif', '.jpg', '.jpeg','svg']) :
cd = os.getcwd().split('/')
fp = self.path.split('/')
img_path = '/'.join(list(set(fp)-set(cd)))
markdown_tag = '![%s](%s)' % (img_path, img_path)
body = [widgets.HTML('<img src="%s"/><p>%s</p> <h3 style="color:green">%s</h3>' % (img_path,img_path, markdown_tag))]
else:
body = tuple([widgets.HTML("-> <h3>%s</h3>" % (self.path,))] + buttons)
box.children = body
'''
f = FileBrowser('optional path')
f.widget()
f.path
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment