Search code examples
pythonpython-3.xtkinterclipboard

tkinter error when copying contents from clipboard in Python


I am writing a python script that will check the clipboard contents and prints them in the console. The below is the script that I am using.

import time
from tkinter import Tk

while True:
    r = Tk()
    result = r.selection_get(selection="CLIPBOARD")
    print(result)
    time.sleep(2)

When I run it without copying any text, I get the below error:

return self.tk.call(('selection', 'get') + self._options(kw))
_tkinter.TclError: CLIPBOARD selection doesn't exist or form "STRING" not defined

I understand that it appears as there are no contents in the clipboard. Once after copying any text, the code runs fine. In order to overcome the issue, I rewrote the code in the following manner:

import time
from tkinter import Tk

r = Tk()
x = 1
while x < 2:
    r.clipboard_clear()
    r.clipboard_append("Starter Text")
    x += 1

while True:
    r.clipboard_clear()
    result = r.selection_get(selection="CLIPBOARD")
    print(result)
    time.sleep(2)

I wrote this so that I can start the file by having a starter text in the clipboard. This will help in stopping the error. Even though it stopped the error from occuring, the code now prints only "Starter Text" in a repeated manner. Even after copying contents into the clipboard, they do not seem to be getting printed.

Can I get some suggestions on how to avoid the error and at the same time print the values whenever I copy something into the clipboard.


Solution

  • I came across with the below script and it helped me to get what I aimed for.

    import time
    from tkinter import Tk
    
    while True:
        r = Tk()
        try:
            result = r.selection_get(selection="CLIPBOARD")
            print(result)
            time.sleep(1)
        except:
            selection = None
    

    I went on with having the try except block with a generic except. @Bryan Oakley's suggestion helped a lot.