共计 1990 个字符,预计需要花费 5 分钟才能阅读完成。
第一版
import tkinter as tk
from tkinter import simpledialog
import time
class CountdownApp:
def __init__(self, master):
self.master = master
master.title("倒计时器")
master.attributes('-topmost', True) # 窗口置顶
# 设置窗口背景颜色为透明
master.configure(bg='systemTransparent')
# 创建标签用于显示倒计时
self.label = tk.Label(master, text="00:00:00", font=("Helvetica", 36), bg='systemTransparent')
self.label.pack(pady=20)
# 获取用户输入的时间
self.seconds = self.get_seconds_from_user()
# 开始倒计时
self.countdown(self.seconds)
def get_seconds_from_user(self):
# 弹出对话框让用户输入秒数
seconds = simpledialog.askinteger("倒计时设置", "请输入倒计时的总秒数:")
return seconds
def countdown(self, seconds):
# 更新标签显示剩余时间
self.label.config(text=self.format_time(seconds))
if seconds > 0:
self.master.after(1000, self.countdown, seconds - 1)
else:
self.label.config(text="时间到!")
def format_time(self, seconds):
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
return f"{hours:02d}:{minutes:02d}:{seconds:02d}"
def main():
root = tk.Tk()
app = CountdownApp(root)
root.mainloop()
if __name__ == '__main__':
main()
报错
import tkinter as tk
from tkinter import simpledialog
import time
class CountdownApp:
def __init__(self, master):
self.master = master
master.title("倒计时器")
master.attributes('-topmost', True) # 窗口置顶
# 设置窗口背景颜色为浅灰色
master.configure(bg='white')
# 设置窗口为半透明
master.wm_attributes("-alpha", 0.95)
# 设置窗口无边框
master.overrideredirect(True)
# 创建标签用于显示倒计时
self.label = tk.Label(master, text="00:00:00", font=("Helvetica", 36), bg='white')
self.label.pack(pady=20)
# 获取用户输入的时间
self.seconds = self.get_seconds_from_user()
# 开始倒计时
self.countdown(self.seconds)
def get_seconds_from_user(self):
# 弹出对话框让用户输入秒数
seconds = simpledialog.askinteger("倒计时设置", "请输入倒计时的总秒数:")
return seconds
def countdown(self, seconds):
# 更新标签显示剩余时间
self.label.config(text=self.format_time(seconds))
if seconds > 0:
self.master.after(1000, self.countdown, seconds - 1)
else:
self.label.config(text="时间到!")
def format_time(self, seconds):
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
return f"{hours:02d}:{minutes:02d}:{seconds:02d}"
def main():
root = tk.Tk()
app = CountdownApp(root)
root.mainloop()
if __name__ == '__main__':
main()
效果非常棒
正文完