O JOE
O JOE

Reputation: 597

How to compulsory close message box for Toplevel window

image for that I have few lines of code here which is login system which works fine but i can click on the Toplevel button multiple times when i provide the wrong password without closing the messagebox.How can i make it so that it has to be closed messagebox before i can make attempt again.

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()

Upvotes: 2

Views: 905

Answers (2)

AD WAN
AD WAN

Reputation: 1474

With hint from @furas this how to implement this:

create another function to the call it when the entry doesn't match and use grab_set method for the Toplevel window tp.grab_set().You can add your customarised image to the Toplevel window as well as message to display in the box(here: i use label to depict that)

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()

Upvotes: 0

Stop harming Monica
Stop harming Monica

Reputation: 12590

You need to make the log window the parent of the dialog:

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

By default it will use the root window (the Tk instance) as the parent which in this case is not what you want.

Upvotes: 2

Related Questions