简体   繁体   English

如何使用tkinter检索复制的文件名?

[英]How to retrieve copied file name with tkinter?

I want to access the filename copied in Windows Explorer (or some other file manager) in my tkinter program. 我想访问tkinter程序中Windows资源管理器(或其他文件管理器)中复制的文件名。 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: 不幸的是,在Windows 7 / Python 3.4.1和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? 我做错了什么还是应该将其报告为错误?

I've run into the same exception, when the clipboard is empty or contains a different type. 当剪贴板为空或包含其他类型时,我遇到了同样的异常。 My solution was to use try & except : 我的解决方案是使用try&除了

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

    print(clipboard)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM