Search code examples
pythonpython-2.7user-interfacetkinter

Python tkinter window loses focus when an info alert is displayed


I am constructing a basic login system in tkinter (python), When the user enters their details to register, I want to display a tkmessagebox that will tell them if there are any errors in their input.

When the GUI loads initially, they are asked if they would like to login or register (works fine). Say the user clicks Register, they are brought to a second screen to enter their details (also works fine). From here, when they enter their details and click register, if the error alert displays, the register part of the GUI loses focus and disappears behind the first part of the GUI where the user would of chosen to go to the register screen.

Is there any way to prevent my child window from loosing focus when an alert is shown?

def registerCheck(self):

    #print('Username: '+ str(self.UN.get()))
    errorList = ''
    if self.UN.get() == '':
        errorList += 'Username cannot be empty\n'
    if len(self.PW.get()) < 4:
        errorList += 'Password must be more than 4 characters long\n'
    if self.PW.get() != self.PWCF.get():
        errorList += 'Passwords do not match\n'
    if len(self.Email.get()) < 5:
        errorList += 'Email is not valid\n'

    if errorList == '':
        tkMessageBox.showinfo(title="About", message="No Errors Found")
    else:
        tkMessageBox.showerror(title="Errors Found!", message=errorList)


    return

Initial Screen

register screen

enter image description here


Solution

  • Make the messagebox a child of the second window, rather than an implicit child of the root window. You can do this by setting the parent attribute when creating the messagebox.

    For example:

    new_window = Toplevel()
    ...
    tkMessageBox.showinfo(parent=new_window, title="About", message="...")