【问题标题】:keyboard.hook_key() stops responding to presses after some kind of error. Only after compiling to .exekeyboard.hook_key() 在出现某种错误后停止响应按下。仅在编译为 .exe 后
【发布时间】:2021-02-08 09:57:10
【问题描述】:

问题仅在编译为.exe 后出现:在keyboard.hook_key ('f7', TranslateAll, suppress = True) 行中按F7 调用函数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', 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

【问题讨论】:

    标签: python keyboard pyautogui keyboard-hook


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-11
      • 1970-01-01
      • 1970-01-01
      • 2020-12-18
      相关资源
      最近更新 更多