tkinter with after loop does not update var in if statement

I have a schedule funtion that needs to check if it is today() and then send mail to the receivers. It need to work so, the user enters begin date then he needs to enter timedelta. When the timedelta is reacht de auto email is sended.

if i use while loop it works fine the email is sending and the timedelta updates again with the given days.
but,,,, you probably know while loop and mainloop in tkinter work not good.

i use now afterloop that calls the function after 2000ms.Now i got a issue that after the timedelta is reacht the email will send but timedelta does not update with the given time and he infinite send whole list of receivers (he need to send 2 of them) and days after again .

cal = DateEntry(master, selectmode = 'day',
            cursor='hand1', date_pattern="yyyy-m-d")
cal.place(x =140,y=20)

#timedelta entri 
date_count_field= Entry(master, width=5)
date_count_field.place(y=20,x=335)

#get & set the begin date
starts = cal.get_date()
cal.set_date(starts)


def starter():
    CleaningSchedule()
    master.after(2000, starter)

def CleaningSchedule():
    starts = cal.get_date()
    global emails , selector
    # master.withdraw()
    now = date.today()
    days_calc = int(date_count_field.get())
    target = starts + timedelta(days=days_calc)
    print('Vandaag is het: ',now, 'Volgende ronde is: ', target)
    if target == now:
        starts += timedelta(days=days_calc)
        target += timedelta(days=days_calc)
        receiver_email = next(selector), next(selector)
        print(receiver_email)

Button(master, text = "Start",
   command =lambda:[starter()], width=10).place(x=410,y = 650)

>Solution :

Each time you call CleaningSchedule() you reset starts to cal.get_date(). You should only initialize it once at the beginning, then update the global variable in the function.

def CleaningSchedule():
    global starts
    # master.withdraw()
    now = date.today()
    days_calc = int(date_count_field.get())
    target = starts + timedelta(days=days_calc)
    print('Vandaag is het: ',now, 'Volgende ronde is: ', target)
    if target == now:
        starts += timedelta(days=days_calc)
        target += timedelta(days=days_calc)
        receiver_email = next(selector), next(selector)
        print(receiver_email)

There’s no need for global email, selector because you never assign these variables in the function (you don’t even use email at all).

Leave a Reply