3

I want to access the filename copied in Windows Explorer (or some other file manager) in my tkinter program. Here's how I'm trying to do this:

from tkinter import *

root = Tk()

def print_filename():
    print(root.clipboard_get(type="FILE_NAME"))

but = Button(root, text="Show filename", command=print_filename)
but.grid()

root.mainloop()

Unfortunately I get same error both in Windows 7/Python 3.4.1 and in Lubuntu 13.10/Python 3.3.2:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python34\lib\tkinter\__init__.py", line 1487, in __call__
    return self.func(*args)
  File "C:\Users\Aivar\Desktop\get_file_from_clipboard.py", line 6, in show_filename
    print(root.clipboard_get(type="FILE_NAME"))
  File "C:\Python34\lib\tkinter\__init__.py", line 587, in clipboard_get
    return self.tk.call(('clipboard', 'get') + self._options(kw))
_tkinter.TclError: CLIPBOARD selection doesn't exist or form "FILE_NAME" not defined

Am I doing something wrong or should I report this as a bug?

Aivar
  • 6,814
  • 5
  • 46
  • 78
  • 1
    `win32clipboard` alternative: http://stackoverflow.com/a/7045591/819417 – Cees Timmerman Dec 02 '14 at 12:36
  • How important is it that the solution work with "some other file manager" (*i.e.* such as Finder on OSX, [Nautilus](https://en.wikipedia.org/wiki/GNOME_Files), etc)? Or would a *windows only solution* be fine for your purposes? – Tersosauros Apr 16 '16 at 02:57
  • @Tersosauros, actually I need cross-platform solution – Aivar Apr 18 '16 at 06:56

1 Answers1

1

I've run into the same exception, when the clipboard is empty or contains a different type. My solution was to use try & except:

def print_filename():
    try:
        clipboard = Tk().clipboard_get(type="FILE_NAME")
    except:
        clipboard = ""

    print(clipboard)
Jan
  • 23
  • 4