snir.tur
snir.tur

Reputation: 451

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. 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. How can I avoid non-text content?

Upvotes: 5

Views: 3117

Answers (1)

Augusta
Augusta

Reputation: 7221

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). 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. That's a string by default, though you can change it with the function's type keyword argument.

Here's an example that builds on Nodak and jonrsharpe's answer and comments:

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.

Upvotes: 1

Related Questions