【问题标题】:How can I break for loop by pressing key?如何通过按键打破循环?
【发布时间】:2020-10-16 05:49:05
【问题描述】:

我编写了这个小程序,它为我在信使中发送垃圾邮件。但如果我愿意,我不能让它停下来。我试图将“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 循环

【问题讨论】:

  • 这能回答你的问题吗? tkinter and time.sleep
  • @jasonharper 好吧,这并不是真正的重复,因为 OP 说他不知道如何使用 .after()
  • 如果你想打破一个循环,你应该检查循环内的一些条件。但是你的代码里面没有这样的代码。
  • 您究竟想如何停止循环?你想输入 shell 还是只想按任意键还是在 tkinter 窗口中按一个键?
  • @TheFluffDragon9 我想通过按我在代码中指定的键来停止它,例如 Esc

标签: python loops for-loop tkinter pyautogui


【解决方案1】:

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

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 代码道歉,但希望您能理解。 我还没有测试过,如果有问题请告诉我。

【讨论】:

  • 谢谢!我没有设法通过按键来停止它,它似乎太复杂了,你的建议没有帮助:(所以我添加了停止按钮并将其绑定到 stop(event) 并且它对我有用!
  • 实际上没有 :( 它不起作用,之前我做了不好的测试,但无论如何谢谢你,我会继续努力让它工作。当按下按钮时,循环继续做它的工作并且最后停止函数调用
猜你喜欢
  • 1970-01-01
  • 2021-11-11
  • 1970-01-01
  • 1970-01-01
  • 2013-08-22
  • 2023-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多