Access the clipboard via Tkinter

sneekula 1 Tallied Votes 14K Views Share

You can accesss the clipboard simply by using the Tkinter GUI toolkit that comes with your Python installation.

Gribouillis commented: interesting +14
''' tk_clipboard_action.py
use Tkinter to get access to the clipboard/pasteboard
tested with Python27/33
'''

try:
    # Python2
    import Tkinter as tk
except ImportError:
    # Python3
    import tkinter as tk

root = tk.Tk()
# keep the window from showing
root.withdraw()

text = "Donnerwetter"
root.clipboard_clear()
# text to clipboard
root.clipboard_append(text)
# text from clipboard
clip_text = root.clipboard_get()

print(clip_text)  # --> Donnerwetter
Gribouillis 1,391 Programming Explorer Team Colleague

It is interesting although I cannot make it work in linux with KDE. However, a search for clipboard in pypi yields a number of results. Among them, pyperclip looks promising. Which is the best module for clipboard access ?

sneekula 969 Nearly a Posting Maven

I simply searched
C:/Python27/Lib/lib-tk/Tkinter.py
or
C:/Python33/Lib/tkinter/init.py
for
clipboard
it's all fairly well documented

I actually needed to use it with a Tkinter program, so it came in handy.

Gribouillis 1,391 Programming Explorer Team Colleague

Hm the documentation speaks about the tk clipboard, which is probably different from the system clipboard. Your code works for me, but I can't use it to paste something into an external window, such as firefox. It doesn't copy anything to the system clipboard.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

On Windows 8.1 it pastes into Google Chrome alright.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Can somebody test this on Linux or OSX ...

''' text_to_clipboard101.py

test it by using paste in your editor or other program

tested with Python34 and Python27   OS = Windows 8.1
'''

import subprocess

def copy2clip(txt):
    '''copy txt to the clipboard'''
    subprocess.Popen(['clip'], stdin=subprocess.PIPE).communicate(txt)

text = "a precipitate is not part of the solution"
# <class 'bytes'> needed for Python3
byte_text = text.encode()

copy2clip(byte_text)
woooee 814 Nearly a Posting Maven

Produces can't find clip error on Slackware and Python 2.7 Linux uses xclip as it does not view the OS and GUI as the same thing, but "Xclip", "xclip", and "xclip -selection c" produced the same error.

Traceback (most recent call last):
  File "./test_1.py", line 108, in <module>
    copy2clip(byte_text)
  File "./test_1.py", line 102, in copy2clip
    subprocess.Popen(['clip'], stdin=subprocess.PIPE).communicate(txt)
  File "/usr/lib64/python/subprocess.py", line 711, in __init__
    errread, errwrite)
  File "/usr/lib64/python/subprocess.py", line 1308, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory
Gribouillis 1,391 Programming Explorer Team Colleague

The corresponding command in linux is xclip, or xsel. This is what pypi modules such as pyperclip do. See the source code here. Notice that in windows, this module has a ctypes.windll solution.
In OSX, subprocess with pbcopy and pbpaste commands are used.

woooee 814 Nearly a Posting Maven

Apparently Fluxbox uses xclipboard so xclip and xsel have to be installed if you want to use them. Unfortunately when doing cross-platform stuff, Linux is not one size fits all.

sneekula 969 Nearly a Posting Maven

I wonder how many different Linux distributions there are?
It would be nice to replace the Windows OS.

Appearently only the Windows machines at SONY got hacked. The finance department used Apple OSX machines and was safe.

Slavi 94 Master Poster Featured Poster

Quite a few, kind of depends on what you are fan of. I am running Elementary OS on my home pc mainly due to the desktop environment that it has(looks like iOS).

Also I have Kali Linux on my laptop(Mainly because it comes with a lot of pentesting tools preinstalled, as I am doing a masters in Computer security) and I was really not fan of the gnome desktop environment so the first thing I did was to change it straight away as soon as I installed it :D

As for clipboard ... I am getting into python now so I've been reading some books and I came accross one called hacking ciphers with python. The book uses pyperclip for copy/paste to/from clipboard. This is the source code from them it also should work on all operating systems as it detects which is the os it is been ran on

import platform, os

def winGetClipboard():
    ctypes.windll.user32.OpenClipboard(0)
    pcontents = ctypes.windll.user32.GetClipboardData(1) # 1 is CF_TEXT
    data = ctypes.c_char_p(pcontents).value
    #ctypes.windll.kernel32.GlobalUnlock(pcontents)
    ctypes.windll.user32.CloseClipboard()
    return data

def winSetClipboard(text):
    text = str(text)
    GMEM_DDESHARE = 0x2000
    ctypes.windll.user32.OpenClipboard(0)
    ctypes.windll.user32.EmptyClipboard()
    try:
        # works on Python 2 (bytes() only takes one argument)
        hCd = ctypes.windll.kernel32.GlobalAlloc(GMEM_DDESHARE, len(bytes(text))+1)
    except TypeError:
        # works on Python 3 (bytes() requires an encoding)
        hCd = ctypes.windll.kernel32.GlobalAlloc(GMEM_DDESHARE, len(bytes(text, 'ascii'))+1)
    pchData = ctypes.windll.kernel32.GlobalLock(hCd)
    try:
        # works on Python 2 (bytes() only takes one argument)
        ctypes.cdll.msvcrt.strcpy(ctypes.c_char_p(pchData), bytes(text))
    except TypeError:
        # works on Python 3 (bytes() requires an encoding)
        ctypes.cdll.msvcrt.strcpy(ctypes.c_char_p(pchData), bytes(text, 'ascii'))
    ctypes.windll.kernel32.GlobalUnlock(hCd)
    ctypes.windll.user32.SetClipboardData(1, hCd)
    ctypes.windll.user32.CloseClipboard()

def macSetClipboard(text):
    text = str(text)
    outf = os.popen('pbcopy', 'w')
    outf.write(text)
    outf.close()

def macGetClipboard():
    outf = os.popen('pbpaste', 'r')
    content = outf.read()
    outf.close()
    return content

def gtkGetClipboard():
    return gtk.Clipboard().wait_for_text()

def gtkSetClipboard(text):
    global cb
    text = str(text)
    cb = gtk.Clipboard()
    cb.set_text(text)
    cb.store()

def qtGetClipboard():
    return str(cb.text())

def qtSetClipboard(text):
    text = str(text)
    cb.setText(text)

def xclipSetClipboard(text):
    text = str(text)
    outf = os.popen('xclip -selection c', 'w')
    outf.write(text)
    outf.close()

def xclipGetClipboard():
    outf = os.popen('xclip -selection c -o', 'r')
    content = outf.read()
    outf.close()
    return content

def xselSetClipboard(text):
    text = str(text)
    outf = os.popen('xsel -i', 'w')
    outf.write(text)
    outf.close()

def xselGetClipboard():
    outf = os.popen('xsel -o', 'r')
    content = outf.read()
    outf.close()
    return content


if os.name == 'nt' or platform.system() == 'Windows':
    import ctypes
    getcb = winGetClipboard
    setcb = winSetClipboard
elif os.name == 'mac' or platform.system() == 'Darwin':
    getcb = macGetClipboard
    setcb = macSetClipboard
elif os.name == 'posix' or platform.system() == 'Linux':
    xclipExists = os.system('which xclip') == 0
    if xclipExists:
        getcb = xclipGetClipboard
        setcb = xclipSetClipboard
    else:
        xselExists = os.system('which xsel') == 0
        if xselExists:
            getcb = xselGetClipboard
            setcb = xselSetClipboard
        try:
            import gtk
            getcb = gtkGetClipboard
            setcb = gtkSetClipboard
        except Exception:
            try:
                import PyQt4.QtCore
                import PyQt4.QtGui
                app = PyQt4.QApplication([])
                cb = PyQt4.QtGui.QApplication.clipboard()
                getcb = qtGetClipboard
                setcb = qtSetClipboard
            except:
                raise Exception('Pyperclip requires the gtk or PyQt4 module installed, or the xclip command.')
copy = setcb
paste = getcb

NOTE:
If you save the file as pyperclip.py and you want to use it as a module for your program it is being called as follows:

import pyperclip
example = '''The Turing test is a test of a machine's ability to exhibit intelligent behavior equivalent to, or indistinguishable from, that of a human'''
pyperclip.copy(example)
TrustyTony commented: Thanks for sharing! +12
TrustyTony 888 pyMod Team Colleague Featured Poster
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.