在Python中从剪贴板复制内容时出现tkinter错误 [英] tkinter error when copying contents from clipboard in Python

查看:60
本文介绍了在Python中从剪贴板复制内容时出现tkinter错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个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.

推荐答案

我遇到了以下脚本,它帮助我获得了目标。

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

我继续尝试try例外,并使用了通用除外。
@Bryan Oakley的建议很有帮助。

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

这篇关于在Python中从剪贴板复制内容时出现tkinter错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆