键盘.hook_key()在出现某种错误后停止对按键的响应。仅在编译为.exe之后

2024-10-01 11:23:42 发布

您现在位置:Python中文网/ 问答频道 /正文

该问题仅在编译为.exe后出现:当按F7调用函数TranslateAll时,在第keyboard.hook_key ('f7', TranslateAll, suppress = True)行中。函数算法:

  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', TranslateAll, 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

Tags: keyfrom文本importselfcountfunctionhook
1条回答
网友
1楼 · 发布于 2024-10-01 11:23:42

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

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

相关问题 更多 >