Search code examples
pythontkinterwidgetmessageboxmainloop

Tkinter mainloop broken, messagebox keeps popping up


class StartUp():
    def __init__(self):
        pass

    def verify(self):
        username = ("s")
        password = ("s")
        
        usernameEntry = usernameVar.get()
        passwordEntry = passVar.get()

        start = StartUp()

        if usernameEntry == username and passwordEntry == password:
            start.login() 
        else: 
            #messagebox.showerror("Error","Wrong Credentials")

            
    def login(self):
        #Create a window
        global usernameVar, passVar
        
        verify = StartUp()
        
        window = Tk()
        window.title("Login")
            
        userPassLabel = Label(window, font="Helvetica 18 bold", text="Royal Mail")
        userPassLabel.grid(row=0, column=0, sticky=W)

        usernameVar = StringVar()
        usernameLabel = Label(window, font="Arial", text="Username:")
        usernameLabel.grid(row=1, column=0, sticky=W)
        usernameEntry= Entry(window, width=30, bg="light blue",textvariable = usernameVar, )
        usernameEntry.grid(row=1, column=1, sticky=W)
            
        passVar = StringVar()
        passLabel = Label(window, font="Arial", text="Password:")
        passLabel.grid(row=2, column=0, sticky=W)
        passEntry= Entry(window, width=30, bg="light blue",textvariable = passVar, show ="●")
        passEntry.grid(row=2, column=1, sticky=W)
        
        b1= Button(window, text="Enter", command=verify.verify())
        b1.grid(row=3, column=0, sticky=W)

        window.mainloop()


start = StartUp()
start.login()

The code seems to not work. The message box will just pop up. The enter button then doesn't work. Not sure what is wrong. I'm very new to OOP so not sure whether it's to do with that.

An additional question is how am I able to carry one variable from an input box in one window/class to another window/class? Is global a viable option or is there a better way I can use .get() from an Entry box.

Thanks for the help


Solution

  • When you use (), you are calling the function immediately. And when you use () with a button, it destroys the purpose of having a button itself. So remove the parenthesis, ().

    b1 = Button(window, text="Enter", command=verify.verify)
    

    When the function gets called, the value inside the entry are empty and hence else is triggered.