Home > OS >  How to open another window and close the current window after clicking button?
How to open another window and close the current window after clicking button?

Time:02-28

I'm new to Graphic User Interface using Python. I was trying to open the Register page after clicking the "Register" button from the Login page. Then, return to the Login page when clicking "Return to Login". But it did not work.

login.py

from tkinter import *
from tkinter import messagebox
from tkinter import ttk
from register import Register

class Login:
    def __init__(self):
        self.loginw = Tk()
        self.loginw.title("Login")
        self.loginw.geometry("500x500")
        
        self.signin = Button(self.loginw,width=20, text="Register", command=self.register)
        self.signin.place(relx=0.5, rely=0.5, anchor=CENTER)

    def register(self):
        self.loginw.quit()
        win = Toplevel()
        Register(win)

w=Login()
w.loginw.mainloop()

register.py

from tkinter import *
from tkinter import messagebox
from tkinter import ttk

class Register:
    def __init__(self):
        self.reg = Tk()
        self.reg.title("Register")
        self.reg.geometry("500x500")
        
        self.revert = Button(self.reg,width=20, text="Return to Login")
        self.revert.place(relx=0.5, rely=0.5, anchor=CENTER)

The error raised up after clicking the Register button

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\me\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 1921, in __call__
    return self.func(*args)
  File "c:\Users\me\Documents\Education\Testing code\login.py", line 18, in register
    Register(win)
TypeError: Register.__init__() takes 1 positional argument but 2 were given

Thank you so much.

CodePudding user response:

When you are calling the Register class's constructor to get a window, you pass the Toplevel instance named win but within the __init__ method of the Register class you are not accepting any arguments to the constructor.

This can be fixed, by accepting another argument in the __init__ method. Further note there is no need to initialize self.reg as tkinter.Tk() then as the Toplevel instance taken as argument will work in it's place.

The Register class definition will change to -:

class Register:
    def __init__(self, win):
        self.reg = win # new.
        self.reg.title("Register")
        self.reg.geometry("500x500")
        
        self.revert = Button(self.reg,width=20, text="Return to Login")
        self.revert.place(relx=0.5, rely=0.5, anchor=CENTER)
        self.reg.mainloop() # new.

Further, Now a new mainloop has to be started for the new window initalized, thus the line self.reg.mainloop() was added.

With the suggested changes in place, the output seems to be as required by the OP -:

enter image description here

  • Related