通过向通义灵码扩展提问,AI自动生成的方式,由最初的“生成一个带界面的时钟程序”,再“添加一个倒计时功能”、“添加音乐播放”、“添加停止播放按钮”一步一步生成了最终的这个程序,现在的AI已经很牛B了

import time
import pygame
from tkinter import Tk, Label, Button, Entry, messagebox

# 一个倒计时计时器程序
# 这个程序使用阿里云【灵码】插件,一步一步优化由AI生成的
# VS code IDE的扩展中安装TONGYI lingma
class TimerClock:
    def __init__(self, master):
        self.master = master
        master.title("Timer Clock")

        pygame.mixer.init()  # 初始化pygame.mixer

        # 创建标签以显示时间
        self.clock_label = Label(master, font=("Arial", 80), bg="black", fg="white")
        self.clock_label.pack(fill="both", expand=1)

        # 创建输入框以输入定时器时长
        self.timer_entry = Entry(master)
        self.timer_entry.pack()

        # 创建按钮以设置/停止定时器
        self.timer_button = Button(master, text="Start Timer", command=self.toggle_timer)
        self.timer_button.pack()

        # 创建按钮以停止音乐
        self.stop_music_button = Button(master, text="Stop Music", command=self.stop_music)
        self.stop_music_button.pack()

        # 定时器相关变量
        self.timer_duration = None
        self.timer_start_time = None
        self.timer_running = False
        self.countdown_id = None  # 存储倒计时ID

        # 初始化并开始更新时间
        self.update_time()

    def toggle_timer(self):
        if not self.timer_running:
            try:
                self.timer_duration = int(self.timer_entry.get())
                if self.timer_duration is not None:
                    self.timer_start_time = time.time()
                    self.countdown_id = self.master.after(0, self.countdown)
                    self.timer_button.config(text="Stop Timer")
                    self.timer_running = True
            except ValueError:
                messagebox.showerror("Error", "Please enter a valid integer.")
        else:
            self.timer_running = False
            self.timer_button.config(text="Start Timer")
            self.master.after_cancel(self.countdown_id)
            self.countdown_id = None
            pygame.mixer.music.stop()

    def countdown(self):
        remaining_time = max(0, self.timer_duration - int(time.time() - self.timer_start_time))
        self.timer_button.config(text=f"Countdown: {remaining_time} sec")
        if remaining_time > 0:
            self.countdown_id = self.master.after(1000, self.countdown)
        else:
            self.timer_alert()

    def timer_alert(self):
        pygame.mixer.music.load('alarm.mp3')
        pygame.mixer.music.play(-1)  # 循环播放音乐
        self.timer_running = False
        self.timer_button.config(text="Start Timer")

    def stop_music(self):
        pygame.mixer.music.stop()
        self.timer_button.config(state='normal')

    def update_time(self):
        current_time = time.strftime("%H:%M:%S")
        self.clock_label.config(text=current_time)
        self.clock_label.after(1000, self.update_time)

if __name__ == "__main__":
    root = Tk()
    my_clock = TimerClock(root)
    root.mainloop()

标签: none

添加新评论