while 循环问题,或者可能是其他问题?

While loop problem, or probably sth else?

Soo 我是一名学生,我对编码还很陌生。我想制作一个在游戏开始时启动计时器的应用程序(特别是游戏 Valorant),我通过搜索游戏进程是否为 运行 来获得它。然后我每 30 分钟收到一次应用程序通知。最后,当我关闭游戏时,应用程序应该暂停计时器并告诉我我玩了多长时间。但是,当我关闭游戏时,计时器不会停止,而且我发现该应用程序永远不会理解进程已停止 运行,即使我使用了 while 循环。这是代码:提前谢谢你!

从 win10toast 导入 ToastNotifier 导入 psutil 导入时间 导入时间表

def show_name(): game = "VALORANT-Win64-Shipping.exe" in (i.name() for i in psutil.process_iter())

if game == True:

    def timer():
        game = "VALORANT-Win64-Shipping.exe" in (i.name() for i in psutil.process_iter())
        m = 0
        s = 0

        while game == True:

            time.sleep(1)
            s += 1
            print(m , s)

            if s == 59:

                m +=1
                s = 0

                if m == 30:
                    toast = ToastNotifier()
                    toast.show_toast("Hello!", "You have been playing for 30 minutes", duration=20)
                elif m == 60:
                    toast = ToastNotifier()
                    toast.show_toast("Hello!", "You have been playing for an hour", duration=20)
                elif m == 90:
                    toast = ToastNotifier()
                    toast.show_toast("Hello!", "You have been playing for 1 hour and 30 minutes", duration=20)
                elif m == 120:
                    toast = ToastNotifier()
                    toast.show_toast("Hello!", "You have been playing for 2 hours", duration=20)
        else:
            toast = ToastNotifier()
            toast.show_toast("Hello!", "You have played for " + str(m) + " minutes and " + str(s) + " seconds!", duration=20)

    schedule.every(4).seconds.do(timer)

schedule.every(4).seconds.do(show_name)

而 1: schedule.run_pending() time.sleep(1)

while 循环不会中断的原因是您没有在 while 循环中更改 game 变量。这意味着如果游戏开始时为 True,while game == Truewhile True 循环相同。您需要在每次迭代中重新验证 游戏

尝试While"VALORANT-Win64-Shipping.exe" in (i.name() for i in psutil.process_iter()):

顺便说一句,你可以直接写While game:而不是While game == True