tkMessageBox在计时器程序中有额外的窗口

时间:2014-11-05 02:56:06

标签: python tkinter tk tkmessagebox

我正在用Python做一个计时器,但是当计时器停止时,我的代码最终显示两个对话框而不是一个。我该怎么做才能避免出现额外的窗口?

以下timer.py的代码:

#!/usr/bin/python
import time
start = time.time()
interval=1

import sys
import tkMessageBox

def showmessage():
    tkMessageBox.showinfo("timer.py", "Timer Complete!")

if __name__ == "__main__":
    if len(sys.argv) > 1:
        ns = {'__builtins__': None}
        seconds=int(eval(str(sys.argv[1]), ns))
        if len(sys.argv) > 2:
            if sys.argv[2]=="mins" or sys.argv[2]=="min":
                seconds=seconds*60

        interval = 1 if seconds < interval else interval
        second=seconds - (time.time() - start) + 0.5
        while second >= 0:
            #In Python 3: print('string', end='\r')
            if int(second/3600) > 0:
                print "\rTime =%3d hrs %02d mins %02d sec" % \
                    (second/3600, (second % 3600)/60, second % 60),
            else:
                print "\rTime =%3d mins %02d sec" % \
                    (second/60, second % 60),

            sys.stdout.flush()
            time.sleep(interval)

            if int(second % 60+0.5) == 0:
                print  #or sys.stdout.write("\n")
            second=seconds - (time.time() - start) + 0.5

        showmessage()
    else:
        print ("Usage: %s [seconds]"      % str(sys.argv[0]))
        print ("       %s [minutes] mins" % str(sys.argv[0]))

1 个答案:

答案 0 :(得分:2)

发生这种情况是因为如果您将showmessage更改为以下内容,则消息框需要父窗口:

def showmessage():
    root = tk.Tk()
    root.withdraw()
    tkMessageBox.showinfo("timer.py", "Timer Complete!")
    root.destroy()

并添加:

import Tkinter as tk

到您的导入,然后您将只获得消息框