Home > Software engineering >  clock works but "python doesn t respond" error after a few seconds
clock works but "python doesn t respond" error after a few seconds

Time:09-27

from tkinter import *
from tkinter import ttk
from time import strftime

clock = Tk()
clock.title("WhatAClock")
clock.geometry("300x400")

notebook = ttk.Notebook()
tab1_timedate = Frame(notebook)
tab2_alarm = Frame(notebook)
tab3_timer = Frame(notebook)

notebook.add(tab1_timedate, text="Time and Date")
notebook.add(tab2_alarm, text="Alarm")
notebook.add(tab3_timer, text="Timer")
notebook.pack(expand=TRUE, fill="both")

def timedate_realtime():
    time_str = strftime('%H:%M:%S')
    l1_timedate.config(text= time_str)
    l1_timedate.after(500, timedate_realtime)
 
def alarm_realtime():
    H_str = strftime("%H")
    M_str = strftime("%M")
    S_str = strftime("%S")
    l1_H.config(text= H_str)
    l2_M.config(text= M_str)
    l3_S.config(text= S_str)
    l1_H.after(500, alarm_realtime)
    l2_M.after(500, alarm_realtime)
    l3_S.after(500, alarm_realtime)
    
l1_timedate = Label(tab1_timedate)
l1_timedate.place(x=100, y=45)
l1_H = Label(tab2_alarm)
l2_M = Label(tab2_alarm)
l3_S = Label(tab2_alarm)
l1_H.grid(column= 1, row= 1)
l2_M.grid(column= 3, row= 1)
l3_S.grid(column= 5, row= 1)

timedate_realtime()
alarm_realtime()                                            
clock.mainloop()

Total noob btw. It was doing fine untill i added the time in the second tab, now it works just as well but only for 3 or 4 seconds! I read it could have to do with a function calling inaccuracy but i still dont t know what to do :(

CodePudding user response:

def alarm_realtime():
    H_str = strftime("%H")
    M_str = strftime("%M")
    S_str = strftime("%S")
    l1_H.config(text= H_str)
    l2_M.config(text= M_str)
    l3_S.config(text= S_str)
    l1_H.after(500, alarm_realtime)
    l2_M.after(500, alarm_realtime)
    l3_S.after(500, alarm_realtime)

Every time alarm_realtime executes, it asks tkinter to run itself three times in 500 milliseconds. Then when each of those execute, they each ask tkinter for another three executions, for a total of nine. 500 milliseconds later, the 9 instances of the function request 27 executions. After a few seconds, you have millions of instances of the function asking to be called.

Instead of calling after three times, call it once.

def alarm_realtime():
    H_str = strftime("%H")
    M_str = strftime("%M")
    S_str = strftime("%S")
    l1_H.config(text= H_str)
    l2_M.config(text= M_str)
    l3_S.config(text= S_str)
    l1_H.after(500, alarm_realtime)
  • Related