[英]How to open another window and close the current window after clicking button?
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.我是使用 Python 的图形用户界面的新手。在从登录页面单击“注册”按钮后,我试图打开注册页面。 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.太感谢了。
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.当您调用
Register
类的构造函数以获取 window 时,您传递了名为win
的Toplevel
实例,但在 Register class 的__init__
方法中,您不接受任何 arguments 给构造函数。
This can be fixed, by accepting another argument in the __init__
method.这可以通过在
__init__
方法中接受另一个参数来解决。 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.进一步注意,不需要将
self.reg
初始化为tkinter.Tk()
然后作为参数的Toplevel
实例将在它的位置工作。
The Register
class definition will change to -: Register
class 定义将更改为 - :
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.此外,现在必须为新的 window 初始化启动一个新的主循环,因此添加了
self.reg.mainloop()
行。
With the suggested changes in place, the output seems to be as required by the OP -:随着建议的更改到位,output 似乎符合 OP 的要求 - :
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.