如何向我的 tkinter 简单时钟项目添加闹钟功能?

哈希姆·拉米尔

我刚刚开始使用 kivy 和 Tkinter 为初学者开发简单的应用程序。最近,我创建了一个可以在桌面上使用的数字时钟程序。它工作正常,因为它很简单,只需几行代码。我想添加一项功能,即警报。任何人都可以请指导我如何去做。

这是我第一次,所以不确定我是否以正确的方式发布了这个问题。所以下面是我用来获取输出的代码。

import tkinter as tk
from tkinter.ttk import *

# I imported strftime to use for formatting time details of the program.
from time import strftime
import datetime

# creating tkinter window
root = tk.Tk()
root.title('Clock')
root.attributes('-topmost', True)  # This line here sets our app to be the 
topmost in the window screen.


# root.attributes('-topmost', False)   When this line is added, the app will 
no longer have that topmost privilege.


# This function will show us the calender on the program.
def datetime():
    string1 = strftime('%d/%b/%Y')  # This line can be joined with the other one  below with \n and it will work.
    lbl1.config(text=string1)
    lbl1.after(1000, datetime)


lbl1 = Label(root, font=('verdana', 20, 'bold'), background='black', 
foreground='#808000')
lbl1.pack(fill=tk.BOTH)
datetime()


# This function is used to display time on our label
def time():
    string = strftime('%H:%M:%S %p')
    lbl.config(text=string)
    lbl.after(1000, time) # updating the label.


# Giving the Label some style.
lbl = Label(root, font=('verdana', 22, 'bold'), background='#050929',
foreground='silver')

# packing the Label to the center.
# of the tkinter window
lbl.pack(anchor=tk.CENTER)
time()
root.mainloop()
阿特拉斯435

对于程序解决方案,只需添加tkinterafter方法。

import tkinter as tk 
import datetime 

def tick():
    showed_time = '' 
    current_time = datetime.datetime.now().strftime("%H:%M:%S")
    if showed_time != current_time:
        showed_time = current_time
        clock.configure(text=current_time)
    clock.after(1000, tick)
    if showed_time == '10:00:00': #10 o'clock print alarm
        print('alarm')
    

root=tk.Tk()

clock = tk.Label(root)
clock.pack()
tick()


root.mainloop()

面向对象的解决方案可能是这样的:

import tkinter as tk
from tkinter import ttk as ttk
import datetime     

root=tk.Tk()

class AlarmClock(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        self.all_alarms = []
        
        self.ini_body()
        self.ini_clock()
        self.ini_mid()
        self.ini_table()

    def ini_body(self):
        self.up_frame = tk.Frame(self)
        self.mid_frame= tk.Frame(self)
        self.dow_frame= tk.Frame(self)

        self.up_frame.pack(side='top')
        self.mid_frame.pack(side='top',fill='x')
        self.dow_frame.pack(side='top')

    def ini_clock(self):
        self.clock = tk.Label(self.up_frame, text='00:00:00')
        self.clock.pack(side='top', fill='x')
        self.tick()
    def tick(self):
        self.showed_time = ''
        self.current_time = datetime.datetime.now().strftime("%H:%M:%S")
        if self.showed_time != self.current_time:
            self.showed_time = self.current_time
            self.clock.configure(text=self.current_time)
        if self.showed_time in self.all_alarms:
            self.invoke_alarm(self.showed_time)
        self.after(1000, self.tick)

    def ini_table(self):
        self.table = ttk.Treeview(self.dow_frame,height=10,columns=('#1'))
        self.table.heading('#0', text='Alarm ID')
        self.table.heading('#1', text='Alarm time')

        self.table.pack()
    def ini_mid(self):
        self.alarm_id = tk.Entry(self.mid_frame,justify='center')
        self.alarm_id.insert('end','Alarm ID')

        self.alarm_time = tk.Entry(self.mid_frame,justify='center')
        self.alarm_time.insert('end','HH:MM')

        self.set_button = tk.Button(self.mid_frame, text='set alarm',
                                    command=self.set_alarm)
        self.cancel_button=tk.Button(self.mid_frame, text='cancel alarm',
                                     command=self.cancel_alarm)

        self.alarm_time.grid(column=1,row=0,sticky='ew')
        self.alarm_id.grid(column=0,row=0, sticky='we')
        self.set_button.grid(column=0, row=1, sticky='ew')
        self.cancel_button.grid(column=1, row=1, sticky='ew')
        self.mid_frame.columnconfigure(0, weight=1)
        self.mid_frame.columnconfigure(1, weight=1)
        
    def set_alarm(self):
        Id = self.alarm_id.get()
        time = self.alarm_time.get()
        self.table.insert('','end', iid=Id, text=Id,
                          values=time, tags=time)
        self.register_alarm()
    def cancel_alarm(self):
        Id = self.alarm_id.get()
        time = self.alarm_time.get()
        if self.table.exists(Id):
            tag = self.table.item(Id, "tags")[0]
            alarm_time=tag+":00"
            self.all_alarms.remove(alarm_time)
            self.table.delete(Id)
        elif self.table.tag_has(time):
            Id = self.table.tag_has(time)[0]
            tag = self.table.item(Id, "tags")[0]
            alarm_time=tag+":00"
            self.all_alarms.remove(alarm_time)
            self.table.delete(Id)
        
    def register_alarm(self):
        self.all_alarms.append(f'{self.alarm_time.get()}:00')
    def invoke_alarm(self, time):
        self.alarm_window = tk.Toplevel()
        self.alarm_window.title('Alarm!')

        self.message = tk.Label(self.alarm_window,
                                text=f"ALARM!! It's {time[:5]} o'clock!")
        self.message.pack(fill='both')

    

alarm = AlarmClock(root)
alarm.pack()


root.mainloop()

希望您喜欢,如果您对此有任何疑问,请告诉我。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章