我制作了这段代码
import win32clipboard as cb # Used to get the windows clipboard content
def getText():
errorMsg = '''No text has been copied to the clipboard.
Copy text to the clipboard and press ENTER:'''
# The text is in the clipboard
cb.OpenClipboard()
text = cb.GetClipboardData()
cb.CloseClipboard()
if text == errorMsg:
raw_input(errorMsg)
text = getText() # Recursive call
cb.OpenClipboard()
cb.SetClipboardText(errorMsg)
cb.CloseClipboard()
return text
如果我将“Hello world”复制到剪贴板并调用getText()两次,我得到:
>>> print getText()
Hello world
>>> print getText()
No text has been copied to the clipboard.
Copy text to the clipboard and press OK: [Copied "Hello" and pressed ENTER]
Hello
现在,如果我尝试将CTRL-V(粘贴)转换为另一个文本编辑器,我会得到“你好” - 这太棒了,但不是我的预期。我希望我的剪贴板中有errorMsg。在剪贴板中保留“hello”并再次调用getText()仍会提示用户将内容复制到剪贴板。
我不想改变代码的行为,但想了解它
答案 0 :(得分:1)
请注意,您提供的代码不会按原样运行。我相信这一行:
if ocrText == errorMsg:
实际应该是:
if text == errorMsg:
此外,当您写入剪贴板时,您应该这样做:
cb.OpenClipboard()
cb.EmptyClipboard()
cb.SetClipboardText(errorMsg)
cb.CloseClipboard()
即,您需要在设置剪贴板数据之前调用EmptyClipboard
。当我进行这些更改时,它似乎按照您的描述工作,错误消息在剪贴板中。