python - 如何通过按键打破循环?
问题描述
我写了这个小程序,它为我在信使中发送垃圾邮件。但如果我愿意,我不能让它停下来。我试图将'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 循环
解决方案
您应该首先添加一个语句来检查它是否应该仍在运行:
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 代码道歉,但希望你能明白。我还没有测试过,所以如果你有问题,请告诉我。
推荐阅读
- youtube-api - 支持 Youtube 剪辑网址
- teradata - 比较多个日期以识别数据库中的重复记录
- flask - 从 Ajax 调用中下载 Brython 中的 excel 文件?
- excel - VBA:复制值,然后以新名称保存工作表的子集
- azure - 显示用户或组权限的 API 或 CLI 在哪里
- asp.net-core - 从 blazor 中的自定义输入选择绑定值到对象的实例字段未在 EditFrom 上提交时分配
- reactjs - 覆盖 MUI 芯片 deleteIcon 颜色
- java - 线程“主”java.lang.NoClassDefFoundError 中的异常:kotlin/Result
- ssas - SCSM - 来自数据立方体的报告不包括时间
- python - 如何使用 Bulkinferrer 从之前在 Tensorflow Extended (TFX) 中推送的模型进行预测