【问题标题】:How to close tkintermessagebox when it's running inside a loop?在循环中运行时如何关闭 tkinter 消息框?
【发布时间】:2021-01-19 15:58:07
【问题描述】:

我正在尝试让 tkinter 消息框每 X 秒出现一次,我成功了,但是按下取消按钮后消息框没有关闭,我该如何解决这个问题?

代码如下:

import Tkinter as tk
import tkMessageBox, time

root = tk.Tk()
root.withdraw()
tkMessageBox.showinfo('TITLE', 'FIRST MESSAGE')

def f():
    tkMessageBox.showinfo('TITLE', 'SECOND MESSAGE')
    tkMessageBox.showinfo('TITLE', 'THIRD MESSAGE')
    time.sleep(15)
while True:
    f()

【问题讨论】:

    标签: python loops tkinter python-2.x messagebox


    【解决方案1】:

    sleep 调用会冻结应用程序。您可以使用after 方法重复函数调用。

    import Tkinter as tk
    import tkMessageBox, time
    
    root = tk.Tk()
    root.withdraw()
    tkMessageBox.showinfo('TITLE', 'FIRST MESSAGE')
    
    def f():
        tkMessageBox.showinfo('TITLE', 'SECOND MESSAGE')
        tkMessageBox.showinfo('TITLE', 'THIRD MESSAGE')
        root.after(15000, f) # call f() after 15 seconds
        
    f()
    
    input('Press Enter to exit')   # or root.mainloop()
    

    【讨论】:

      【解决方案2】:

      一般来说,您不应该在 tkinter 应用程序中调用 time.sleep(),因为这样做会干扰模块自己的事件处理循环。相反,您应该使用不带callback 函数参数的通用小部件after() 方法。

      此外,您可以使您的代码更多 "data-driven" 以减少对代码的修改。

      以下是实现上述两个建议的示例
      (并且适用于 Python 2 和 3):

      try:
          import Tkinter as tk
          import tkMessageBox
      except ModuleNotFoundError:  # Python 3
          import tkinter as tk
          import tkinter.messagebox as tkMessageBox
      
      
      DELAY = 3000  # Milliseconds - change as desired.
      MESSAGE_BOXES = [
          ('Title1', 'First Message'),
          ('Title2', 'Second Message'),
          ('Title3', 'Third Message'),
      ]
      
      root = tk.Tk()
      root.withdraw()
      
      def f():
          for msg_info in MESSAGE_BOXES:
              tkMessageBox.showinfo(*msg_info)
              root.after(DELAY)
          tkMessageBox.showinfo('Note', "That's all folks!")
      
      f()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-03-16
        • 1970-01-01
        • 1970-01-01
        • 2020-09-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-27
        相关资源
        最近更新 更多