简体   繁体   English

使用Python和Tkinter从剪贴板复制

[英]Copy from clipboard using Python and Tkinter

I'm trying to take a string from the Windows clipboard and paste it into a listbox in a Tkinter GUI. 我正在尝试从Windows剪贴板中取一个字符串并将其粘贴到Tkinter GUI的列表框中。 It works great until trying to copy a image. 在尝试复制图像之前,它很有效。

clipboardData = root.selection_get(selection="CLIPBOARD")
listbox.insert(0, clipboardData)

I have tried to use Tkinter, pyperclip and clipboard. 我曾尝试使用Tkinter,pyperclip和剪贴板。 How can I avoid non-text content? 如何避免非文本内容?

Using Tkinter , I would use a try..except block to insert the clipboard data where it exists and ignore it where it doesn't (or, optionally, add some default value). 使用Tkinter ,我会使用try..exceptinsert剪贴板数据insert到存在的位置,并在不存在的地方忽略它(或者,可选地,添加一些默认值)。 This doesn't specifically revoke any image-type clipboard contents, but it will reject anything that isn't in myTkObject.clipboard_get() 's expected format. 这并没有特别撤销任何图像类型的剪贴板内容,但它拒绝任何不符合myTkObject.clipboard_get()预期格式的内容。 That's a string by default, though you can change it with the function's type keyword argument. 默认情况下,这是一个字符串,但您可以使用函数的type关键字参数更改它。

Here's an example that builds on Nodak and jonrsharpe's answer and comments: 这是一个基于Nodak和jonrsharpe的答案和评论的例子:

from Tkinter import Tk
myTkObject = Tk()
try:
    listbox.insert(0, myTkObject.clipboard_get())
except Tkinter.TclError:
    pass  # Instead of do-nothing, you can insert some default value if you like.

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

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