Created
April 13, 2015 11:12
-
-
Save mic-e/2b2681b7dca31488aec1 to your computer and use it in GitHub Desktop.
Python GTK file chooser
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
#!/usr/bin/env python3 | |
from gi.repository import Gtk | |
class FileChooserError(Exception): | |
pass | |
class FileChooser(Gtk.FileChooserDialog): | |
def __init__(self, parent=None, name="choose file"): | |
Gtk.FileChooserDialog.__init__( | |
self, | |
name, | |
parent, | |
Gtk.FileChooserAction.OPEN, | |
(Gtk.STOCK_CANCEL, | |
Gtk.ResponseType.CANCEL, | |
Gtk.STOCK_OPEN, | |
Gtk.ResponseType.OK)) | |
def choose(self): | |
response = self.run() | |
if response == Gtk.ResponseType.OK: | |
return self.get_filename() | |
elif response in {Gtk.ResponseType.DELETE_EVENT, | |
Gtk.ResponseType.CANCEL}: | |
raise FileChooserError("aborted") | |
else: | |
raise FileChooserError(str(Gtk.ResponseType(response))) | |
def __enter__(self): | |
return self | |
def __exit__(self, type, value, traceback): | |
self.destroy() | |
def choose_file(): | |
with FileChooser(None) as fch: | |
return fch.choose() | |
while True: | |
print(choose_file()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment