0

我做了这个代码

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(粘贴)到另一个文本编辑器中,我会得到“Hello”——这很棒,但不是我所期望的。我希望在我的剪贴板中有 errorMsg。在剪贴板中保留“hello”并再次调用 getText() 仍会提示用户将内容复制到剪贴板。

我不想改变代码的行为,但想理解它

4

1 回答 1

1

请注意,您提供的代码不会按原样运行。我相信这条线:

if ocrText == errorMsg:

实际上应该是:

if text == errorMsg:

此外,当您写入剪贴板时,您应该这样做:

cb.OpenClipboard()
cb.EmptyClipboard()
cb.SetClipboardText(errorMsg)
cb.CloseClipboard()

即,您需要EmptyClipboard在设置剪贴板数据之前调用。当我进行这些更改时,它似乎按照您的描述工作,错误消息在剪贴板中。

于 2013-07-18T14:54:15.313 回答