目前,我正在编写一个程序,它将执行一些操作(例如,不断地计数数字),直到将某些内容输入到显示的对话框中为止。
但是,每当我尝试这样做时,程序会在等待输入时冻结,因此在我试图在后台运行的计数过程中不会取得任何进展。
是否有任何方法让定时器在后台连续运行,以便在5分钟内,计数器立即停止,对话框消失?这是我的代码的基本框架。我使用tkinter对话框作为输入,并尝试创建一个将在后台运行的计时器。
from time import *
from tkinter import *
from tkinter import messagebox
from tkinter import simpledialog
while timer<300:
sleep(1)
timer += 1
ROOT = Tk()
ROOT.withdraw()
USER_INP = simpledialog.askstring(title="Code Required",
prompt="What's the Code?:")最好没有外部模块,但如果没有,那就好了。(预先谢谢:)
从tkinter导入*从tkinter导入simpledialog root = Tk() root.withdraw() def疑问():simpledialog.askstring(title="Code Required“),prompt=”代码是什么?“) ## root.after(在root.after()中添加了5000,root.destroy()#,以便在设定时间root.after(3000 )后尝试并终止它,在3000 ms(3秒) root.after(100000,root.destroy()) #尝试等待10秒之后,它才会中断,但这没有显示对话框中的任何内容。
发布于 2020-09-09 21:41:00
下面是一个带有tkinter的基本代码,它使对话框在5秒后弹出。
from tkinter import *
from tkinter import simpledialog
root = Tk()
root.withdraw()
def ask():
simpledialog.askstring(title="Code Required",
prompt="What's the Code?:")
root.after(5000, root.destroy) #added in the root.after() to try and terminate it after set time
root.after(3000,ask) #triggers ask() after 3000 ms(3 seconds)
#root.after(10000, root.destroy) # tried to wait 10 seconds before it breaks but this doesn't show the dialog box any more
root.mainloop()在这里,after()在给定的时间后触发一个函数,即3000 ms(3秒),这样您也可以调整计时器。这只是一个例子,你可以编辑更多的你喜欢。
为什么使用after() while 而不是while和计时器?
这是因为while循环会干扰tkinter mainloop(),导致窗口没有响应,因此不建议使用while或time.sleep()。相反,您也可以通过tkinter或threading使用内置的threading方法。
这里是关于after()**:** 的更多内容。
它采用两个位置参数,主要是func
ms和ms (以毫秒为单位),在此之后指定的函数将为triggered.
func --它是在指定的ms完成后触发的函数。警告:要记住根窗口没有被破坏,它只是隐藏,所以只要根窗口没有被破坏,程序就会继续在后台运行,所以您必须将窗口带回来并关闭它,以便任务结束。出于这个原因,我在那里添加了root.destroy()。
Take a look here for a bit more understanding on after()
希望它能消除你的疑虑,如果有任何错误,请告诉我。
干杯
https://stackoverflow.com/questions/63819335
复制相似问题