Tkinter TkMessageBox not closing after click OK

这一生的挚爱 提交于 2019-12-04 05:52:46

Try calling root.update() before returning from the function. That will process all pending Tk/X window events.

(ideally, you'd establish a main event loop before displaying the window, but that assumes that your entire program is event driven, which may not always work.)

Bryan Oakley

You have to call root.mainloop() to enable the program to respond to events.

A. Rodas

One problem on your code is that you create a new Tk element each time you call the function window_warn. This might not be the cause of your issue, but creating multiple Tk elements is a bad practise that should be avoided. For instance, initialize the root element at the beginning and leave only the call to showwarning:

root = Tkinter.Tk()
root.withdraw()

def window_warn():
    '''This function will throw up a window with some text'''
    tkMessageBox.showwarning("New Case", "You have a new case\n Please restart pycheck")
    return

print "Just started newcase check"
while True:
    # ...

I did it tis way:

import Tkinter as tk
import tkMessageBox
root = tk.Tk()
root.withdraw()
t = tkMessageBox.askyesno ('Title','Are you sure?')
if t:
    print("Great!!!")
    root.update()
else:
    print("Why?")
    root.update()
Aleksandar Krumov

Another solution is to track if the tk.messagebox has occurred, and if it has just break/continue/pass to skip over the re-occurring tk.messagebox:

Flag = False
if Flag: 
    messagebox.showerror("Error", "Your massage here.")
    Flag = True
else:
    break

I propose this because I had issues with other solutions proposed on StackOverflow as I don't have a dedicated root.mainloop() but only have self.mainloop() within the class Root()

My root looks like this and the massage event is generated within some of the inner classes, where I have no access to self.root:

    class Root(tk.Tk):
        def __init__(self):
            tk.Tk.__init__(self)
            ....
            class 1..
            class 2..
            self.mainloop()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!