我无法实现停止无限循环

问题描述 投票:0回答:1

我正在为游戏创建一个脚本,该脚本会在指定的坐标处自动启动鼠标击键。 使用键盘库(用于启动程序的热键)和鼠标库(用于在指定坐标处按下并移动鼠标光标)。我想在按下某个键时实现循环停止,但它无法正常工作。 如果可以的话请告诉我如何实现。

`import sys

import mouse as ms
import keyboard as kb
import time

def stew():
    ms.move(890, 130, absolute=True, duration=0.15)
    ms.click("right")
    ms.move(970, 130, absolute=True, duration=0.15)
    ms.click("right")
    ms.move(800, 130, absolute=True, duration=0.15)
    ms.click("right")
    ms.move(640, 420, absolute=True, duration=0.15)
    ms.click("right")
    ms.move(530, 520, absolute=True, duration=0.15)
    ms.click("left")

kb.wait("F7")
    while True:
    stew()
    time.sleep(4.7)`

我尝试使用 While 循环,每次循环结束时计数器都会递增,但这并不完全是我所需要的。 当按下某个键时需要停止整个循环(或关闭程序)

python keyboard
1个回答
0
投票

似乎您正在尝试循环重复执行

stew
函数,直到按下特定键为止。但是,您当前的实施存在一些问题。
if kb.is_pressed("F7"):
检查位于循环内部,这意味着直到循环的第一次迭代之后才会检查它,并且循环将无限期地继续下去。

要解决此问题,我建议添加一个

running
标志来控制循环。您可以最初将标志设置为
True
并保持循环运行,直到标志设置为
False
。此外,您可以注册一个热键 (F7),按下时将
running
标志设置为
False
。这应该允许您在按下 F7 时停止循环并退出程序。

这是更正后的代码:

# Use a flag to control the loop
running = True

# Define a function to stop the program
def stop_program(e):
    global running
    running = False

# Register the hotkey to stop the program
kb.add_hotkey('F7', stop_program)

# Run the loop until the flag is False
while running:
    stew()
    time.sleep(4.7)
© www.soinside.com 2019 - 2024. All rights reserved.