获取剪贴板文本时获取NoneType错误

时间:2017-04-23 16:10:15

标签: python clipboard ctypes

Ctrl+C任何文本中,在Windows(7)中获取此错误:

  

回溯(最近一次调用最后一次):文件“T:\ Desktop \ nutty.py”,行   45,在       selected_word = get_clip()文件“T:\ Desktop \ nutty.py”,第30行,在get_clip中       clip = str(text.value.decode(“utf-8”))AttributeError:'NoneType'对象没有属性'decode'

from tkinter import Tk
import ctypes, time, os

def set_clip(string=""):
    r = Tk()
    r.withdraw()
    r.clipboard_clear()
    r.clipboard_append(string)
    print("Set data:"+string)
    r.destroy()

def clr_clip():
    r = Tk()
    r.withdraw()
    r.clipboard_clear()
    r.destroy()

def get_clip():
    global clip
    CF_TEXT = 1

    kernel32 = ctypes.windll.kernel32
    user32 = ctypes.windll.user32

    user32.OpenClipboard(0)
    if user32.IsClipboardFormatAvailable(CF_TEXT):
        data = user32.GetClipboardData(CF_TEXT)
        data_locked = kernel32.GlobalLock(data)
        text = ctypes.c_char_p(data_locked)
        clip = str(text.value.decode("utf-8"))
        kernel32.GlobalUnlock(data_locked)
    else:
        clip = "null"
    user32.CloseClipboard()
    return clip

fps=10
previous=""
previous_set_word=""
end=False
clr_clip()
while not end:
    vocab = open("vocab.txt", 'r').readlines()

    selected_word = get_clip()
    if selected_word != previous:
        print("Data:"+selected_word)
        for line in range(len(vocab)):
            word = vocab[line].strip("\n")
            if selected_word == word and not vocab[line] == previous_set_word:
                set_clip(vocab[line+1].strip("\n"))
                previous_set_word = vocab[line+1]
    previous = selected_word
    time.sleep(1/fps)

我不知道为什么会发生这种情况,因为我被告知这样可以获得数据!

0 个答案:

没有答案