首页 > 解决方案 > 如何通过按键打破循环?

问题描述

我写了这个小程序,它为我在信使中发送垃圾邮件。但如果我愿意,我不能让它停下来。我试图将'try / except:KeyboardInterrupt'放在循环中,但它没有帮助。

我需要 python 以某种方式检查我是否按下了某个键,如果按下了它会中断循环。我也知道after()Tkinter 中有一个方法,我应该使用它而不是time.sleep,但我的尝试失败了。这是我的代码:

from tkinter import *
import time
import pyautogui

root = Tk()
root.title('Typer')
text_field = Text(root, height=20, width=40)
button = Button(text='----Start----')


def typer(event):
    text = text_field.get("1.0",END)
    time.sleep(5)
    for i in text.split(' '):  
        pyautogui.write(i)
        pyautogui.press('enter')


button.bind('<Button-1>', typer)

text_field.pack()
button.pack()
root.mainloop()

更新:我设法通过这样做来time.sleep()改变after()

def typer(event):
    def innertyper():
        for i in text.split(' '):
            pyautogui.write(i)
            pyautogui.press('enter')
    text = text_field.get("1.0",END)
    root.after(5000, innertyper)

但我仍然无法打破 for 循环

标签: pythonloopsfor-looptkinterpyautogui

解决方案


您应该首先添加一个语句来检查它是否应该仍在运行:

def typer(event):
    global running
    running = True
    text = text_field.get("1.0",END)
    time.sleep(5)
    for i in text.split(' '):
        if running == False: #Will break the loop if global variable is changed
            break
        pyautogui.write(i)
        pyautogui.press('enter')

然后是几个选项可供选择;您可以使用 tkinter 的绑定(仅在 tkinter 窗口中有效)

root.bind("<Escape>", stop)

def stop(event):
    global running
    running = False

如果您不想点击进入窗口,我建议您使用键盘pip install keyboard

要么做:

keyboard.on_press_key("Esc", stop)

或者:

def typer(event):
    text = text_field.get("1.0",END)
    time.sleep(5)
    for i in text.split(' '):
        if keyboard.is_pressed("Esc"): #Will break the loop if key is pressed
            break
        pyautogui.write(i)
        pyautogui.press('enter')

我为 janky 代码道歉,但希望你能明白。我还没有测试过,所以如果你有问题,请告诉我。


推荐阅读