如何强制关闭 Toplevel window 的消息框

How to compulsory close message box for Toplevel window

image for that 我这里有几行代码,它是登录系统,工作正常,但是当我提供错误的密码而不关闭 messagebox 时,我可以多次单击 Toplevel 按钮。我怎样才能做到这一点它必须关闭 messagebox 才能再次尝试。

from tkinter import *
from tkinter import messagebox


def top():
    if entry1.get() == "333":
       log.destroy()
       root.deiconify()
    else:
       messagebox.showerror("error", "try again")


root = Tk()
root.geometry("300x300")

log = Toplevel(root)
log.geometry("200x200")


label1 = Label(log, text="password")
entry1 = Entry(log)
button1 = Button(log, text="login", command=top)

label1.pack()
entry1.pack()
button1.pack(side="bottom")

lab = Label(root, text="welcome bro").pack()


root.withdraw()
root.mainloop()

您需要使日志 window 成为对话框的父级:

messagebox.showerror("error", "try again", parent=log)

默认情况下,它将使用根 window(Tk 实例)作为父级,在这种情况下这不是您想要的。

根据@furas 的提示,如何实现:

创建另一个函数以在条目不匹配时调用它并使用 grab_set 方法作为 Toplevel window tp.grab_set()。您可以将自定义图像添加到 Toplevel window 以及要在框中显示的消息(此处:我使用标签来描述)

from tkinter import *
from tkinter import messagebox



def dialog():  #  this function to call when entry doesn't match 
    tp = Toplevel(log)
    tp.geometry("300x100")
    tp.title('error')
    tp.grab_set()  # to bring the focus to the window for you to close it
    tp.resizable(width=False, height=False)
    l = Label(tp, text="try again\n\n\n\n add your customarize image to the window")
    l.pack()


def top():
    if entry1.get() == "333":
    log.destroy()
    root.deiconify()
else:
    dialog()  # being called here 


root = Tk()
root.geometry("300x300")

log = Toplevel(root)
log.geometry("200x200")


label1 = Label(log, text="password")
entry1 = Entry(log)
button1 = Button(log, text="login", command=top)

label1.pack()
entry1.pack()
button1.pack(side="bottom")

lab = Label(root, text="welcome bro").pack()


root.withdraw()

root.mainloop()