如何通过按键中断循环?

How can I break for loop by pressing key?

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

我需要 python 以某种方式检查我是否按下了某个键,如果按下了则中断循环。我也知道 Tkinter 中有一个 after() 方法,我应该使用它而不是 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循环

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

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 window 中工作)

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

def stop(event):
    global running
    running = False

如果你不想点击进入 window 我建议使用键盘 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')

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