快节奏的时代,时间管理是我们要面临的问题之一,无论是演讲比赛、微课大赛、课堂授课、各类汇报都要在规定的时间内完成特定的任务,那么如何能够准确地把握时间呢?我们这里借助于人工智能工具ChatGPT,开发出多个倒计时工具,使用的语言包括了python、VBA和Html,用户可以选择在不同的场景,结合个人的实际情况来使用它们。
一、采用Python编写
1. 功能简介
Python是一种比较灵活的胶水语言,可以自定以各种功能,包括前端显示、时间设定、计时提醒等,唯一的不足是需要打包成exe,有时它还会被360识别为病毒软件,在不同的终端下可能会要求不同的打包方式。本人以windows为例,利用python中的tkinter框架,开发出如下的倒计时工具:
Python倒计时工具
其主要特点是:支持快捷键操作;字体大小可调;界面可最小化;到期有提醒;时间可以在一小时内设定;操作比较简单。
2. 样例代码
import tkinter as tk
from tkinter import messagebox
class CountdownTimer:
def __init__(self, root):
self.root = root
self.root.title("倒计时1.0 By Gordon")
self.root.attributes("-topmost",1)
self.root.geometry("500x320")
self.timelabel = tk.Label(self.root, text="设置倒计时时间",font=("Helvetica", 14,'bold'))
self.timelabel.pack()
self.minute_var = tk.StringVar(root)
self.minute_var.set("25")
self.minute_option = tk.OptionMenu(root, self.minute_var, *range(1,60))
self.minute_option.pack()
self.remaining_time = 25 * 60 # 默认倒计时时间为25分钟
self.is_running = False
self.is_paused = False
#设置日钟显示
self.timer_label = tk.Label(self.root, text="", font=("Helvetica", 120,"bold"),fg="blue")
self.timer_label.pack(expand=True, fill=tk.BOTH, pady=20)
button_frame = tk.Frame(self.root)
button_frame.pack(side=tk.TOP,anchor="n")
# 设置 Scale 控件在同一行
self.scale = tk.Scale(button_frame, from_=50, to=400, width=15, orient='horizontal', command=self.resize)
self.scale.set(120)
self.scale.pack(expand=True, fill=tk.BOTH) # 确保 Scale 在同一行
self.start_button = tk.Button(button_frame, text="开始(S)", width=10, font=("times new romman", 11),command=self.start_timer)
self.start_button.pack(side=tk.LEFT)
self.reset_button = tk.Button(button_frame, text="重置(R)", width=10, font=("times new romman", 11),command=self.reset_timer)
self.reset_button.pack(side=tk.LEFT)
self.pause_button = tk.Button(button_frame, text="暂停(P)", width=10, font=("times new romman", 11),command=self.pause_timer)
self.pause_button.pack(side=tk.LEFT)
self.exit_button = tk.Button(button_frame, text="退出(Q)", width=10, font=("times new romman", 11), command=self.ui_quit)
self.exit_button.pack(side=tk.LEFT)
self.exit_button = tk.Button(button_frame, text="最小化(Q)", width=10, font=("times new romman", 11), command=self.ui_quit)
self.exit_button.pack(side=tk.LEFT)
self.update_timer()
self.root.bind('<r>',self.reset_timer)
self.root.bind('<s>',self.start_timer)
self.root.bind('<p>',self.pause_timer)
self.root.bind('<q>',self.ui_quit)
def resize(self,ev = None):
# 监控窗口是不是最大化,最大化则字体变大,否则为55号字
if self.root.state() == 'zoomed':
self.timer_label.config(font = 'Helvetica -%d bold' % self.scale.get())
elif not self.root.state() == 'zoomed':#self.root.state() == 'iconic':
self.timer_label.config(font = 'Helvetica -%d bold' % 120)
self.after_id = self.root.after(1000, self.resize)
def ui_quit(self,envent = None):
self.root.after_cancel(self.after_id) # 取消所有 after 调用
self.root.destroy()
self.root.quit()
def update_timer(self):
if self.remaining_time == 0:
self.timer_label.configure(text="Time's up!",font=("Helvetica", 200),fg="red")
messagebox.showinfo("倒计时完成", "时间已到!")
self.is_running = False
self.is_paused = True
minutes = int(self.minute_var.get())
self.remaining_time = minutes * 60
minutes = self.remaining_time // 60
seconds = self.remaining_time % 60
self.timer_label.configure(text=f"{minutes:02d}:{seconds:02d}",fg="blue")
if self.is_running and not self.is_paused:
self.remaining_time -= 1
self.after_id = self.root.after(1000, self.update_timer)
def start_timer(self,event=None):
if not self.is_running:
minutes = int(self.minute_var.get())
self.remaining_time = minutes * 60
self.is_running = True
self.is_paused = False
self.pause_button.configure(text="暂停(P)")
def reset_timer(self,event = None):
self.is_running = False
self.remaining_time = int(self.minute_var.get()) * 60 # 默认倒计时时间为1分钟
#self.timer_label.configure(text="")
self.pause_button.configure(text="暂停(P)")
def pause_timer(self,event = None):
if self.is_paused:
self.is_paused = False
self.pause_button.configure(text="暂停(P)")
else:
self.is_paused = True
self.pause_button.configure(text="继续(P)")
if __name__ == "__main__":
root = tk.Tk()
countdown_timer = CountdownTimer(root)
root.mainloop()
二、VBA编写的倒计时
1. 功能介绍
采用VBA编写主要好处是不需要利用了电脑自带的Excel软件,在多个终端平台可以使用,打开即用,基本不挑终端,只要你在Excel中点【文件】-【选项】-【信任中心】-【启用所有宏】即可。此软件以xlsm结尾,打开即可展示,双击界面可以设定倒计时的时间,支持1小时之内倒计时设置。
启用所有宏
软件的界面比较小,考虑在播放课件时使用,但是目前的问题是前端显示无法满足,因此功能还有一定的欠缺。
VBA倒计时工具
2. 代码展示
以下是相关代码供参考:
窗体设置名称为CountdownForm,里面的代码如下:
' 模块顶部变量
Public remainingSeconds As Long
Public isRunning As Boolean
Private targetTime As Date
' 初始化窗体,放右下角并启动倒计时
Private Sub UserForm_Initialize()
Me.Left = Application.UsableWidth - Me.Width
Me.Top = Application.UsableHeight - Me.Height
StartCountdown
End Sub
' 启动倒计时(默认25分钟)
Public Sub StartCountdown()
remainingSeconds = 25 * 60
targetTime = Now + TimeSerial(0, 0, remainingSeconds)
isRunning = True
UpdateLabel
ScheduleTick True
End Sub
' 更新时间显示
Public Sub UpdateLabel()
Dim h As Long, m As Long, s As Long
h = remainingSeconds \ 3600
m = (remainingSeconds Mod 3600) \ 60
s = remainingSeconds Mod 60
lblTime.Caption = Format(h, "00") & ":" & Format(m, "00") & ":" & Format(s, "00")
End Sub
' 安排下一次计时,默认1秒后触发
Private Sub ScheduleTick(Optional force As Boolean = False)
Dim scheduledTime As Date
If (isRunning And remainingSeconds > 0) Or force Then
scheduledTime = Now + (1.15 / 86400)
Application.OnTime scheduledTime, "CountdownForm_Tick"
End If
End Sub
' 每秒调用的计时过程(全局入口)
Public Sub CountdownForm_Tick()
CountdownForm.Tick
End Sub
' Tick:精准计算剩余时间,并处理时间耗尽
Public Sub Tick()
If isRunning Then
remainingSeconds = DateDiff("s", Now, targetTime)
If remainingSeconds <= 0 Then
remainingSeconds = 0
isRunning = False
UpdateLabel
MsgBox "时间到!", vbInformation
Else
UpdateLabel
ScheduleTick
End If
End If
End Sub
' 双击时间标签:重新设置倒计时
Private Sub lblTime_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
Dim inputStr As String
Dim inputMin As Long
inputStr = InputBox("请输入倒计时时间(分钟),范围1~60:", "设置倒计时", CStr(remainingSeconds \ 60))
If inputStr = "" Then Exit Sub ' 用户取消
If IsNumeric(inputStr) Then
inputMin = CLng(inputStr)
If inputMin >= 1 And inputMin <= 60 Then
remainingSeconds = inputMin * 60
targetTime = Now + TimeSerial(0, 0, remainingSeconds)
isRunning = True
UpdateLabel
ScheduleTick force:=True
Else
MsgBox "请输入1到60之间的数字!", vbExclamation
End If
Else
MsgBox "请输入有效的数字!", vbExclamation
End If
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
Application.DisplayAlerts = False ' 不提示是否保存
Application.Quit ' 直接退出 Excel
End Sub
在ThisWorkbook中设置如下代码
Private Sub Workbook_Open()
Application.Visible = False
CountdownForm.Show vbModeless
' 然后设置窗体为活动窗口
AppActivate CountdownForm.Caption
End Sub
在模块一中设置如下代码
Public Sub CountdownForm_Tick()
On Error Resume Next
CountdownForm.Tick
End Sub
三、采用Html+CSS+JS编写倒计时
1. 功能介绍
这个工具使用场景可设置在学校,界面可以设置成卡通模式,支持设定时分秒,字体可以调整大小,也可以全屏展示,同时时间到时还可以响铃。
Html+CSS+JS倒计时工具
2. 代码展示
以下是html代码
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
<title>倒计时</title>
</head>
<body>
<div class="container">
<h1>倒计时</h1>
<div id="timer">10:00</div>
<div class="controls">
<input type="number" id="hours" value="0" min="0" class="time-input">
<label for="hours">小时</label>
<input type="number" id="minutes" value="10" min="0" max="59" class="time-input">
<label for="minutes">分钟</label>
<input type="number" id="seconds" value="0" min="0" max="59" class="time-input">
<label for="seconds">秒</label>
</div>
<input type="range" id="fontSize" min="100" max="520" value="35" step="2">
<span id="fontSizeValue">520</span> px
</br><button id="setButton">设置时间</button>
<button id="startPauseButton">开始倒计时</button>
<button id="fullscreenButton">全屏显示</button>
</div>
<script src="script.js"></script>
</body>
</html>
以下是script.js代码展示
let timer;
let totalTime = 10 * 60; // 默认10分钟,以秒为单位
let isRunning = false;
// 创建一个音频元素来播放铃声,并预加载
const bellSound = new Audio("上课铃声.mp3");
bellSound.play().then(() => bellSound.pause()).catch(error => {
console.log("音频预加载失败,等待用户交互", error);
});
function startTimer() {
if (isRunning) return;
isRunning = true;
// 由于用户交互,重新尝试预加载音频
bellSound.play().then(() => bellSound.pause());
document.getElementById('startPauseButton').textContent = '暂停';
timer = setInterval(() => {
if (totalTime <= 0) {
clearInterval(timer);
isRunning = false;
document.getElementById('startPauseButton').textContent = '开始倒计时';
/*alert("倒计时结束!");*/
bellSound.play(); // 倒计时结束播放铃声
return;
}
totalTime--;
const minutes = Math.floor(totalTime / 60);
const seconds = totalTime % 60;
document.getElementById('timer').textContent =
`${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
}, 1000);
}
function pauseTimer() {
clearInterval(timer);
isRunning = false;
document.getElementById('startPauseButton').textContent = '继续倒计时';
}
function toggleTimer() {
if (isRunning) {
pauseTimer();
} else {
startTimer();
}
}
function setTimer() {
const hours = parseInt(document.getElementById('hours').value) || 0;
const minutes = parseInt(document.getElementById('minutes').value) || 0;
const seconds = parseInt(document.getElementById('seconds').value) || 0;
totalTime = hours * 3600 + minutes * 60 + seconds;
const displayMinutes = Math.floor(totalTime / 60);
const displaySeconds = totalTime % 60;
document.getElementById('timer').textContent =
`${String(displayMinutes).padStart(2, '0')}:${String(displaySeconds).padStart(2, '0')}`;
}
function toggleFullscreen() {
if (!document.fullscreenElement) {
document.documentElement.requestFullscreen();
updateFontSize(); // 进入全屏时更新字号
} else {
if (document.exitFullscreen) {
document.exitFullscreen();
}
}
}
function changeFontSize() {
const fontSize = document.getElementById('fontSize').value;
document.getElementById('timer').style.fontSize = fontSize + 'px';
document.getElementById('fontSizeValue').textContent = fontSize; // 更新字号显示
}
function updateFontSize() {
const fontSize = document.getElementById('fontSize').value;
document.getElementById('timer').style.fontSize = fontSize + 'px';
}
// 为按钮添加事件监听
document.getElementById('setButton').addEventListener('click', setTimer);
document.getElementById('startPauseButton').addEventListener('click', toggleTimer);
document.getElementById('fullscreenButton').addEventListener('click', toggleFullscreen);
document.getElementById('fontSize').addEventListener('input', changeFontSize);
以上是css代码展示
body {
font-family: 'Comic Sans MS', Times, serif;
background-color: #e6f7ff; /* 淡蓝色背景 */
background-image: url('background.jpg'); /* 替换为您背景图片的路径 */
background-size: cover;
background-position: center;
background-repeat: no-repeat;
background-attachment: fixed;
color: blue; /* 字体颜色 */
margin: 0;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
label {
font-weight: bold;
}
.container {
text-align: center;
}
#timer {
font-size: 180px; /* 初始字号 */
margin: 20px 0;
}
.controls {
margin: 20px 0;
}
.time-input {
width: 60px; /* 设置输入框宽度一致 */
margin: 0 5px;
}
button {
margin: 5px;
padding: 10px 15px;
font-size: 16px;
cursor: pointer;
border: none;
background-color: #4CAF50; /* 按钮背景色 */
color: white; /* 按钮字体颜色 */
border-radius: 5px;
}
button:hover {
background-color: #45a049; /* 按钮悬停效果 */
}
四、三种倒计时工具下载
为方便大家学习使用,我把三种工具都打包,大家可以点击以下地址进入下载
倒计时工具集成(python VBA Html).zip
链接: https://pan.baidu.com/s/1GN10P33xv9laPcwLJkXIPg?pwd=6bt4 提取码: 6bt4
复制这段内容后打开百度网盘手机App,操作更方便哦
五、学后总结
1. 三种语言各有优势,实现的方法各异,但是殊途同归。但实现的过程我一借助了AI为实现。而且就其准确率和功能性来说,Python编写的倒计时工具更加准确,个性化更强一些。
2. 在不同的场景下就可以选用不同的软件,比如在微课比赛中我们可以使用python的软件,功能齐全。在学校场景可以用html网页版的,可以在大展幕上显示。作为VBA练习,可以了解一下VBA的倒计时。
3. 事期可能考虑支持设定多个倒计时,或者是定时功能,但不同的时间段提醒用户,这样时间管理更加高效。如:在课堂铃声这个方面就可以用这种方法。