1

I am new at python. I am using python 2.7. I want to have messagebox to notify me on every 50 seconds. when I write this:

import sys
import time
import threading

if sys.version_info < (3,0):
        import Tkinter as tkinter
        import tkMessageBox as mbox
else:
        import tkinter
        import tkinter.messagebox as mbox

window = tkinter.Tk()
window.wm_withdraw()

def loop():
    threading.Timer(20.0, loop).start()
    mbox.showinfo('my app',time.ctime())

loop()

But when I press OK application freeze. What I am doing wrong?

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
Vladimir Yanakiev
  • 1,240
  • 1
  • 16
  • 25
  • 1
    Take a look at `window.mainloop()`... – campovski Sep 04 '17 at 11:25
  • Possible duplicate of [How to use the after method to make a periodical call?](https://stackoverflow.com/questions/44085554/how-to-use-the-after-method-to-make-a-periodical-call) – Right leg Sep 04 '17 at 11:42

1 Answers1

2

You forgot to call window.mainloop(). This method triggers the main loop of the widget, which processes the events, and allows interaction with the widget and its children.

In addition, you should use the after widget method rather than other timers. This method allows you to schedule a call to a method. You might wan to have a look at this post for a more complete explanation of the after method.

The following code implements the loop function with the after method, and runs the main loop by calling window.mainloop().

def loop(root):
    mbox.showinfo('my app',time.ctime())
    root.after(50000, lambda: loop(root))

window = tkinter.Tk()
window.wm_withdraw()

loop(window)
window.mainloop()

Note that the loop function takes a widget as parameters, that will be your window. This is needed, because the after method needs to be called on a widget.

Additionally, the after method takes a callback as second parameter, and I found it easier to pass it as a lambda function. The latter is tantamount to calling root.after(50000, f) where f has been defined by def f(): return loop(root).

Right leg
  • 16,080
  • 7
  • 48
  • 81
  • approved this answer. Can you tell me where I can see " threading.Timer vs after method" – Vladimir Yanakiev Sep 04 '17 at 12:39
  • @VladimirYanakiev I'm not sure if there is any explicit reason *against* `threading.Timer`, but since `tkinter` provides a way to handle scheduling, it should be used for the sake of uniformity. The fewer modules you use, the more constancy and compatibility you can expect across the functions. – Right leg Sep 04 '17 at 12:41