gpt4 book ai didi

python - 如何使倒计时显示在 tkinter 窗口而不是我的 cmd 中?

转载 作者:行者123 更新时间:2023-11-28 21:33:54 30 4
gpt4 key购买 nike

这段代码基本上允许用户设置倒计时(以秒为单位),当倒计时归零时会出现一条消息。我是 tkinter 和 python 的初学者,所以我不知道如何让我的倒计时显示在 tkinter 窗口中,因为它只显示在 cmd 中。

import time
import tkinter as Alarm
class test(Alarm.Frame):
def __init__(self, parent):
Alarm.Frame.__init__(self, parent)
self.prompt = Alarm.Label(self, text="Enter seconds:", anchor="w")
self.entry = Alarm.Entry(self)
self.output = Alarm.Label(self, text="")
self.submit = Alarm.Button(self, text="Submit", command = self.startTimer)
self.prompt.pack(side="top", fill="x")
self.entry.pack(side="top", fill="x", padx=20)
self.output.pack(side="top", fill="x", expand=True)
self.submit.pack(side="right")
def countdown(k,q):
j=q
k=0
while True:
if(j>=0):
print(str(j),end="\r")
time.sleep(1)
j-=1
if(j==-1):
break
if(j==-1):
print("Alarm!", end="\r")
time.sleep(1)
def startTimer(self):
try:
i = int(self.entry.get())
self.countdown(i)
except ValueError:
print("Please enter whole digits only in all boxes")
if __name__ == "__main__":
root = Alarm.Tk()
test(root).pack(fill="both", expand=True)
root.mainloop()

最佳答案

如果你想显示一些动画,after() 是可行的方法。不要使用 time.sleep(),因为它会卡住您的 mainloop

import tkinter as Alarm

class test(Alarm.Frame):
def __init__(self, parent):
Alarm.Frame.__init__(self, parent)
self.prompt = Alarm.Label(self, text="Enter seconds:", anchor="w")
self.entry = Alarm.Entry(self)
self.output = Alarm.Label(self, text="Start")
self.submit = Alarm.Button(self, text="Submit", command = self.startTimer)
self.prompt.pack(side="top", fill="x")
self.entry.pack(side="top", fill="x", padx=20)
self.output.pack(side="top", fill="x", expand=True)
self.submit.pack(side="right")

def countdown(self, s):
if s==0:
self.output.configure(text="Alarm!")
return
self.output.configure(text=str(s))
s -= 1
self.output.after(1000, lambda: self.countdown(s))

def startTimer(self):
try:
i = int(self.entry.get())
self.countdown(i)
except ValueError:
print("Please enter whole digits only in all boxes")

if __name__ == "__main__":
root = Alarm.Tk()
test(root).pack(fill="both", expand=True)
root.mainloop()

Demo

关于python - 如何使倒计时显示在 tkinter 窗口而不是我的 cmd 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54077716/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com