微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

发生某种错误后,keyboard.hook_key停止响应按键仅在编译为.exe

如何解决发生某种错误后,keyboard.hook_key停止响应按键仅在编译为.exe

仅在编译为.exe后出现问题:在按{em> F7 的行keyboard.hook_key ('f7',Translateall,suppress = True)调用函数Translateall功能算法:

  1. 图书馆pyperclip从剪贴板中提取文本
  2. 图书馆googletrans翻译文本
  3. pyperclip将翻译后的文本插入剪贴板

一切正常,但是,编译为.exe后,经过10次函数调用后,keyboard.hook_key()停止响应。

我尝试在keyboard.hook_key ()错误地重新分配 F7 ,但是那也不起作用。

可能是什么问题?

代码有问题的部分:(您可以尝试运行它以查看其工作原理,然后使用pyinstaller“ NameOfCode.py”查看我所描述的问题)

from PyQt5.QtWidgets import *
from PyQt5.QtCore import QSize
from googletrans import Translator
import keyboard
import googletrans
import pyperclip

count = 0                         #function operation counter

Translateall_count = 0            #variable,for single
                                  #triggering a function when a button is pressed

def Translateall(event):
    global Translateall_count
    global count
    Translateall_count += 1
    if Translateall_count != 2:

        #main algorithm 

        translator = Translator()

        data = pyperclip.paste()

        result = translator.translate(data,dest='ru')

        pyperclip.copy(result.text)

        Translateall_count = 1
        count += 1
        print(f'Actuation №{count}\n')


class MainWindow(QMainWindow):
    def __init__(self):

        QMainWindow.__init__(self)
        self.setFixedSize(QSize(480,180))
        self.setwindowTitle("test")

        #binding F7 to a function Translateall
        keyboard.hook_key('f7',suppress=True)


if __name__ == "__main__":
    import sys
 
    app = QApplication(sys.argv)
    mw = MainWindow()
    mw.show()
    sys.exit(app.exec())

运行.py文件时的输出

Actuation №1
Actuation №2
Actuation №3
Actuation №4
#until the user finishes work

运行.exe文件时的输出

#7 Actuations
Actuation №8
#the function stops being called

解决方法

问题出在函数调用行keyboard.hook_key('f7',TranslateAll,suppress=True)

要解决该问题,只需将suppress参数的值从 True更改为False

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。