0

I have a continuously running program that periodically reads an sqlite database. It calls a function to display messages in a tkinter window by checking certain criteria, and then it goes to sleep. My problem is that the window freezes when I try to close it (using the quit() method). It could be that, in this case, root.mainloop() is not the last statement of the program. (I need to display a pop-up window at regular intervals).

I believe multithreading is not a solution because tkinter should not be run in a separate thread.

What is the right approach to this problem?

Following is the code -

def display_reminders(task_names):

    root = Tk()

    root.title('Reminder')
    root.geometry('-0-40')
    root.minsize(width=300,height=100)
    root.attributes("-topmost", True)
    root.rowconfigure(0, weight=1)
    root.columnconfigure(0, weight=1)

    for key, name, dt in task_names:
        Label(root, text=name).grid(padx=20, pady=20, sticky=NW)
    btn = Button(root, text='Ok', command=root.quit)
    btn.grid(pady=5)
    btn.bind('<Return>', lambda e: root.quit())

    root.mainloop()


def check_for_reminders(missed_flag=False):

    # logic to read database and check if reminder should be displayed

    display_reminders(task_names)

check_for_reminders(True)
time.sleep(60 - int(datetime.datetime.now().strftime('%S')))
while True:
    check_for_reminders()
    # We subtract the number of seconds from 60 because having only
    # time.sleep(60) results in the number of seconds past the minute creeping
    # up.
    time.sleep(60 - int(datetime.datetime.now().strftime('%S'))) 
debashish
  • 1,374
  • 1
  • 19
  • 29
  • Show us the code which manages the closing of the window. – Goralight Dec 14 '17 at 10:32
  • 1
    don't use `sleep` in GUI and any framework which use `mainloop` because it blocks `mainloop` which gets events from system, sends events to widgets, redraw widget, eyc. - and all in loop. In `tkinter` use `root.after()` to run function periodically. – furas Dec 14 '17 at 10:32
  • **Don't add a external function to mainloop** – dsgdfg Dec 14 '17 at 10:38
  • @furas My main window is being created in a function (see the code) and that function is being called at intervals of 1 minute. In this situation, how can I use `root.after()` ? – debashish Dec 14 '17 at 12:25
  • you didn't show code before - now I see you use it in different way than I expected. How it works when you remove all logic which read database and use fake data ? If works without problems then problem can be in logic and we can't say anything more. – furas Dec 14 '17 at 13:18
  • try `root.destroy()` – furas Dec 14 '17 at 13:22
  • `root.destroy()` works. Thanks! One thing to note is that in my code `root.mainloop()` is not the last logical line. This post https://stackoverflow.com/a/29159217/7992397 says that it has to be the last line. I wonder if this could be a problem. – debashish Dec 15 '17 at 02:43

0 Answers0