即使程序在两天之间关闭,也会在x天后通知

时间:2018-03-29 08:46:37

标签: python-3.x datetime tkinter notifications

from tkinter import *
from datetime import datetime, timedelta 
import pickle
from tkinter import messagebox

filename = "file.pk" #filename data stored as dic = {time:[name,item]}

root = Tk()

t = IntVar()
i = StringVar()
n = StringVar()


def Notification_On_Completing(n, i, t):
    return messagebox.showinfo("Completed", "Name:- {}, Item:-{}, in Days:-{}".format(n, i, t)) 


def Check_If_Time_Is_Over():   #my actual problem is in this function 

    with open(filename, "rb") as f: 
        dic = pickle.load(f)

    now = datetime.now()

    for i, j in dic: #trying to loop and check if the time == now() 
            if i == now: 
                Notification_On_Completing(j[0], j[1], i) #if its true return the key which is equal with its value

            elif i != now: #if now time i am tryinng to show how much time left
                print(i - now, "Time has left for name:-{}, item:-{}".format(j[0],j[1]))
            else:
                root.after(10000, Check_If_Time_Is_Over)

def SaveTheDaysToNotify():

    now = datetime.now()
    time = t.get()  # days to wait beforer notifying
    item = i.get()  #item name    
    name = i.get()  #name 

    end = now + timedelta(days=time)  #adding today with the number of days to notify

    with open(filename.pk, "rb") as f: # avoiding the overide of the files
        dic = pickle.load(f)

    dic= {end:[name, item]}  # saving a days to notify as dic which will also show the name , and item
    with open("file.pk", "wb") as f: #keeping record of the time time to notify
        pickle.dump(dic, f)
    Check_If_Time_Is_Over()


#Gui starts from here

time1 = Entry(root,textvariable=t).pack()  #taking entry as of time, name and item
name1 = Entry(root,textvariable=n).pack()

item1 = Entry(root,textvariable = i).pack()

ss =按钮(root,text ="已完成",command = SaveTheDaysToNotify).pack()#adding到pickle数据库,格式为字典,如dic = {time:[name,item]}

root.mainloop() Check_If_Time_Is_Over()

我正在尝试创建一个程序,它将以时间,项目,名称作为条目。时间将被视为显示通知的天数。例如,程序应在x天后显示通知并不断检查是否即使程序将在几天或几小时间隔内关闭并重新打开特定时间,x天也已到来。

1 个答案:

答案 0 :(得分:0)

您可以存储输入的日期以及文件中的数字。您可以使用datetime.timedelta为您的时间添加天数。

每次运行程序时,请检查是否存在此特殊文件,阅读日期和编号,检查日期+ number_days是今天还是今天之前并创建通知。

如果你的程序不是startet,它就不会显示任何内容。如果你的程序没有在它之间关闭它不会显示任何东西 - 后一种情况可以用一些计时器完成并在TKs主循环内定期检查(记住小时,如果改变,再次检查文件或smth ......)

示例:

import os

from datetime import datetime , timedelta

fn = "myfile.txt"
date = None
days = None

def delDateFile():
    """Remove date file after showing notification, so next time user will
    be asked to input days again."""
    os.remove(fn)

def writeDate(d:int):
    """Adds d days to now(), writes it to file and returns the date."""
    date = datetime.now()  + timedelta(days = d)
    with open(fn,"w") as f: # overwriting existing file
        f.write(stringFromDate(date ))
    return date.date()

def dateFromString(s):
    """Parses a string into a date. Format: '%Y-%m-%d'"""
    try:
         return datetime.strptime(s,'%Y-%m-%d').date()
    except ValueError:
        print("Malformed date")
        return writeDate(-1)        

def stringFromDate(d):
    """Makes a string from a date. Format: '%Y-%m-%d'"""
    return datetime.strftime(datetime.now(),'%Y-%m-%d')


def needToShowNotification():
    def checkIfFileExistsAndExtractDate():
        """Reads a date from file, returns date from file or None if no file exists."""
        if os.path.exists(fn):
            with open(fn,"r") as f:
                date = dateFromString(f.readline())
            return date 
        return None

    def askForDaysAndWriteFile():
        """Asks for days and writes a file with the new date. Malformed input produces date of yesterday"""
        try:
            days = int(input("Days? "))
        except (ValueError, EOFError): # malformed input: empty or no number
            days = -1

        return writeDate(days) 


    # prefer date from file, else ask and write file
    date = checkIfFileExistsAndExtractDate() or askForDaysAndWriteFile()

    return date < datetime.now().date()


def Notif():
    print("------------------")
    print("-- NOTIFICATION --")
    print("------------------")
    delDateFile()

if needToShowNotification():
    Notif()
else:
    print("Go ahead, no need to notify")

使用负天数输入运行它以查看通知(或删除创建的文件)