最近指导学生写了一个倒计时小工具,现在跟大家进行分享,代码和运行结果如下,需要的库,可以对照程序自行下载,主要功能就是电脑端的倒计时功能。
左边电池显示的是倒计时总秒数。
import tkinter as tk
import time
import pyttsx3
import datetime
from PIL import ImageTk, Image
import requests
# 初始化语音引擎
engine = pyttsx3.init()
# 初始化主窗口
root = tk.Tk()
root.title("倒计时工具")
# 设置窗口尺寸
root.geometry("1366x768")
# 添加背景图片
image = Image.open("background.jpg")
image = image.resize((1366, 768))
background_image = ImageTk.PhotoImage(image)
background_label = tk.Label(root, image=background_image)
background_label.place(x=0, y=0, relwidth=1, relheight=1)
# 定义倒计时变量和状态变量
countdown = 0
countdown1=0
countdown2=0
countdown3=0
is_counting = False
# 定义函数:开始倒计时
def start_countdown():
global countdown, is_counting
if not is_counting:
try:
countdown1= int(hours.get())
countdown2=int(minutes.get())
countdown3=int(seconds.get())
countdown=countdown1*3600+countdown2*60+countdown3
except ValueError:
engine.say("输入的时间不正确,请输入一个整数!")
engine.runAndWait()
return
if countdown <=0:
engine.say("输入的时间必须大于0!")
engine.runAndWait()
return
is_counting = True
countdown_label.config(text=str(countdown))
start_button.config(text="倒计时")
countdown_task()
# 定义函数:停止倒计时
def stop_countdown():
global is_counting
is_counting = False
start_button.config(text="开始")
# 定义函数:倒计时任务
def countdown_task():
global countdown, is_counting
if countdown == 0:
engine.say("倒计时结束")
engine.runAndWait()
is_counting = False
start_button.config(text="倒计时")
return
countdown -= 1
countdown_label.config(text=str(countdown))
countdown_label2.config(text=format_time(countdown))
if is_counting:
root.after(1000, countdown_task)
# 定义函数:设置倒计时时间
def set_countdown_time():
global is_counting
if not is_counting:
try:
countdown1= int(hours.get())
countdown2=int(minutes.get())
countdown3=int(seconds.get())
countdown = countdown1*3600+countdown2*60+countdown3
except ValueError:
engine.say("输入的时间不正确,请输入一个整数!")
engine.runAndWait()
return
if countdown <=0:
engine.say("输入的时间必须大于0!")
engine.runAndWait()
return
countdown_label.config(text=str(countdown))
# 定义函数:设置新的倒计时时间
def reset_countdown_time():
global is_counting
is_counting = False
start_button.config(text="倒计时")
countdown_label.config(text="0")
#将倒计时的秒数转换成时分秒的形式来显示倒计时
def format_time(seconds):
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
return "{:02d}:{:02d}:{:02d}".format(hours, minutes, seconds)
# 添加组件:输入框、开始按钮、停止按钮、倒计时标签、时间标签、设置按钮、重置按钮
#小时
hours= tk.Entry(root, width=10, font=("Arial", 15),bg="green", fg="yellow")
hours.insert(0, "输入小时数:")
hours.bind("<FocusIn>", lambda event: hours.delete(0, "end") if hours.get() == "输入小时数:" else None)
hours.bind("<FocusOut>", lambda event: hours.insert(0, "输入小时数:") if hours.get() == "" else None)
hours.pack()
hours.place(x=500, y=650)
#分钟
minutes= tk.Entry(root, width=10, font=("Arial", 15),bg="green", fg="yellow")
minutes.insert(0, "输入分钟数:")
minutes.bind("<FocusIn>", lambda event: minutes.delete(0, "end") if minutes.get() == "输入分钟数:" else None)
minutes.bind("<FocusOut>", lambda event: minutes.insert(0, "输入分钟数:") if minutes.get() == "" else None)
minutes.pack()
minutes.place(x=620, y=650)
#秒
seconds= tk.Entry(root, width=8, font=("Arial", 15),bg="green", fg="yellow")
seconds.insert(0, "输入秒数:")
seconds.bind("<FocusIn>", lambda event: seconds.delete(0, "end") if seconds.get() == "输入秒数:" else None)
seconds.bind("<FocusOut>", lambda event: seconds.insert(0, "输入秒数:") if seconds.get() == "" else None)
seconds.pack()
seconds.place(x=740, y=650)
start_button = tk.Button(root, text="开始倒计时", command=start_countdown,bg="green", fg="white")
start_button.place(x=533, y=534)
stop_button = tk.Button(root, text="停止", command=stop_countdown,bg="green", fg="white")
stop_button.place(x=610, y=534)
countdown_label = tk.Label(root,text="倒计时", font=("隶书", 75),bg="green", fg="yellow")
countdown_label.place(x=89, y=252)
#剩余时间计算输出
countdown_label2= tk.Label(root,text="剩余时间", font=("隶书", 60),bg="green", fg="yellow")
countdown_label2.place(x=930,y=260)
time_label = tk.Label(root, text=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), font=("Arial", 24),bg="green", fg="yellow")
time_label.place(x=510, y=600)
set_button = tk.Button(root, text="设置", command=set_countdown_time,bg="green", fg="white")
set_button.place(x=700, y=534)
reset_button = tk.Button(root, text="重置", command=reset_countdown_time,bg="green", fg="white")
reset_button.place(x=750, y=534)
def update_time():
time_label.config(text=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
root.after(1000, update_time)
update_time()
# API Key
api_key = '12b2817fbec86915a6e9b4dbbd3d9036'
# Get weather data from OpenWeatherMap API
def get_weather(city):
# API endpoint
url = f'http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}'
# Make request
response = requests.get(url)
# Parse response data
data = response.json()
# Return weather data
return data['weather'][0]['description'], data['main']['temp'], data['main']['humidity']
# Create labels to display weather data
label_city = tk.Label(root, text='城市:',font=("黑体", 15),bg="green", fg="yellow")
label_city.place(x=100, y=500)
label_desc = tk.Label(root, text='天气:',font=("黑体", 15),bg="green", fg="yellow")
label_desc.place(x=100, y=530)
label_temp = tk.Label(root, text='温度:',font=("黑体", 15),bg="green", fg="yellow")
label_temp.place(x=100, y=560)
label_humidity = tk.Label(root, text='湿度:',font=("黑体", 15),bg="green", fg="yellow")
label_humidity.place(x=100, y=590)
# Create entry box for user to enter city
entry_city = tk.Entry(root,font=("黑体", 15),bg="green", fg="yellow")
entry_city.place(x=100,y=620)
# Function to get and display weather data
def show_weather():
# Get city from user input
city = entry_city.get()
# Get weather data
desc, temp, humidity = get_weather(city)
# Display weather data
label_city.config(text=f'城市: {city}')
label_desc.config(text=f'天气: {desc}')
label_temp.config(text=f'温度: {temp} °F')
label_humidity.config(text=f'湿度: {humidity} %')
# Create button to get weather data
button = tk.Button(root, text='输入城市名获取天气信息', command=show_weather,font=("隶书", 15),bg="green", fg="yellow")
button.place(x=100, y=650)
class TextAnimation:
def __init__(self, master):
self.master = master
self.canvas = tk.Canvas(master, width=350, height=250,bg="green" )
self.canvas.place(x=920, y=430)
self.text = self.canvas.create_text(100, 120, text="好好学习\n天天向上", font=("黑体", 60) )
self.animate_text()
def animate_text(self):
x, y = self.canvas.coords(self.text)
if x > self.canvas.winfo_width():
x = -self.canvas.bbox(self.text)[2]
self.canvas.coords(self.text, x+2, y)
self.master.after(60, self.animate_text)
text_animation = TextAnimation(root)
# 运行 GUI
root.mainloop()