【问题标题】:Python - How can I press a button(shift+F1) to activate a while True (key and mouseclick) and deactivate it on the same button?Python - 如何按下按钮(shift+F1)来激活一段时间 True(键和鼠标单击)并在同一个按钮上停用它?
【发布时间】:2021-08-14 10:05:25
【问题描述】:

我在 python 中有这段代码(使用 vcode)

import keyboard
import pyautogui
import time

def mine():
    while True:
        try:
            if keyboard.is_pressed("shift+F1"):
                while True:
                    print("2")
                    pyautogui.click()
                    time.sleep(30)  
                    keyboard.press_and_release('1')
if __name__ == "__main__":
  mine()

我希望 while True: 在我按下当前有效的 shift+F1 时播放和重复。现在 while True: 应该在我再次按 shift+F1 时自行结束,如果我再次按它,​​while True: 应该再次开始,依此类推。我该怎么做,或者我在寻找什么?我是编码和python新手,所以我不太了解

编辑:

现在看起来像这样,但我仍然没有得到我要找的东西......我卡在 else: pass 中(当我放置一个打印时,会无限重复打印并且 shift+f1不再起作用了)

import keyboard
import pyautogui
import time

def mine():
    while True:
        try:
            if keyboard.is_pressed("shift+F1"):
                while True:
                    if keyboard.is_pressed("shift+F1"):
                        print("ende")
                        break
                    else:
                        print("else")
                        pyautogui.click()
                        time.sleep(30)  
                        keyboard.press_and_release('1')
            else:
                pass   
        except:
            pass        
if __name__ == "__main__":
  mine()

【问题讨论】:

    标签: python multithreading while-loop keyboard-events


    【解决方案1】:

    设置一个标志,当你按下 shift+F1 时它会改变标志条件。 shift+F1 就像一个开/关按钮。 使用 time.sleep(0.5)(half second) 来防止一次按下 shift+F1 的多个标志更改

    import time
    def mine():
        flag = True
        while True:
            if(flag):
                print("do something like pyautogui and pressandrelease 1")
            if(flag==True and keyboard.is_pressed("shift+F1")):
                flag = False
                time.sleep(0.5)
            elif(flag == False and keyboard.is_pressed("shift+F1")):
                flag = True
                time.sleep(0.5)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-01
      • 2011-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-05
      • 2019-06-01
      • 1970-01-01
      相关资源
      最近更新 更多