Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save draperjames/90403fd013e332e4a14070aab3e3e7b0 to your computer and use it in GitHub Desktop.
Save draperjames/90403fd013e332e4a14070aab3e3e7b0 to your computer and use it in GitHub Desktop.
Select files button for Jupyter notebook
import traitlets
from IPython.display import display
from ipywidgets import widgets
from tkinter import Tk, filedialog
class SelectFilesButton(widgets.Button):
"""A file widget that leverages tkinter.filedialog."""
def __init__(self, *args, **kwargs):
"""Initialize the SelectFilesButton class."""
super(SelectFilesButton, self).__init__(*args, **kwargs)
# Add the selected_files trait
self.add_traits(files=traitlets.traitlets.List())
# Create the button.
self.description = "Select Files"
self.icon = "square-o"
self.style.button_color = "orange"
# Set on click behavior.
self.on_click(self.select_files)
@staticmethod
def select_files(b):
"""Generate instance of tkinter.filedialog.
Parameters
----------
b : obj:
An instance of ipywidgets.widgets.Button
"""
# Create Tk root
root = Tk()
# Hide the main window
root.withdraw()
# Raise the root to the top of all windows.
root.call('wm', 'attributes', '.', '-topmost', True)
# List of selected fileswill be set to b.value
b.files = filedialog.askopenfilename(multiple=True)
b.description = "Files Selected"
b.icon = "check-square-o"
b.style.button_color = "lightgreen"
@AlexisPrel
Copy link

Thanks for sharing!

Personally I like to do this little modification

L10:def __init__(self, *args, do_on_select=None, **kwargs):
L21:if do_on_select is not None: b.do = do_on_select
L39:b.do(b)

This avoids writng another button.on_click and permits to raise an error inside do_on_select before turning the button to green.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment