Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中从剪贴板复制内容时出现tkinter错误_Python_Python 3.x_Tkinter_Clipboard - Fatal编程技术网

在Python中从剪贴板复制内容时出现tkinter错误

在Python中从剪贴板复制内容时出现tkinter错误,python,python-3.x,tkinter,clipboard,Python,Python 3.x,Tkinter,Clipboard,我正在编写一个python脚本,它将检查剪贴板内容并在控制台中打印它们。下面是我正在使用的脚本 import time from tkinter import Tk while True: r = Tk() result = r.selection_get(selection="CLIPBOARD") print(result) time.sleep(2) 当我在不复制任何文本的情况下运行它时,会出现以下错误: return self.tk.call(('se

我正在编写一个python脚本,它将检查剪贴板内容并在控制台中打印它们。下面是我正在使用的脚本

import time
from tkinter import Tk

while True:
    r = Tk()
    result = r.selection_get(selection="CLIPBOARD")
    print(result)
    time.sleep(2)
当我在不复制任何文本的情况下运行它时,会出现以下错误:

return self.tk.call(('selection', 'get') + self._options(kw))
_tkinter.TclError: CLIPBOARD selection doesn't exist or form "STRING" not defined
据我所知,剪贴板中似乎没有任何内容。复制任何文本后,代码都可以正常运行。为了克服这个问题,我以以下方式重写了代码:

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)
导入时间
从tkinter导入Tk
r=Tk()
x=1
当x<2时:
r、 剪贴板_clear()
r、 剪贴板\附加(“起始文本”)
x+=1
尽管如此:
r、 剪贴板_clear()
结果=r.selection\u get(selection=“剪贴板”)
打印(结果)
时间。睡眠(2)
我写这篇文章是为了在剪贴板中有一个起始文本来启动文件。这将有助于停止错误。即使它阻止了错误的发生,代码现在也只以重复的方式打印“起始文本”。即使将内容复制到剪贴板中,它们似乎也不会被打印出来

我可以得到一些关于如何避免错误的建议,同时在我将某些内容复制到剪贴板时打印这些值

您无法避免错误,因为这是设计的行为,但您可以处理错误

import tkinter as tk
...
try:
    selection = r.selection.get(selection="CLIPBOARD")
except tk.TclError:
    selection = None
...

我看到了下面的脚本,它帮助我实现了我的目标

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
我继续使用带有泛型except的try-except块。
@布莱恩·奥克利的建议帮助很大

你的“起始文本”技巧实际上并不能解决问题——如果用户在你的程序运行时将图像或其他非文本项复制到剪贴板怎么办?当剪贴板上没有文本时,您需要使用
try
/
except
捕获并忽略错误。我不知道你为什么看不到剪贴板的更改-也许Tkinter Main循环需要运行才能工作。嗨,我使用了代码
,而True:r=Tk()r.clipboard\u clear()try:result=r.selection\u get(selection=“clipboard”)打印(result)时间。睡眠(2)除了Tk.tclError:selection=None
,但我收到一个错误声明-
AttributeError:type对象“Tk”没有属性“tclError”
@mbvee:该错误消息似乎是不言自明的。
Tk
的实例没有属性
TclError
。这不是我的代码所显示的。我的代码清楚地显示了使用tkinter模块中的
TclError
。另外,绝对没有理由在无限循环中调用
Tk()
。它只需要创建一次。感谢您的回复。我错过了进口声明。在文件的开头,我还有tkinter import Tk的
导入时间。