我正在写密码。我需要一种方法将命令放入一个按钮,以便当我单击登录按钮时它会破坏窗口并获取用户名和密码。我查看了这个网站,并没有这些方法适合我,所以我需要明确我需要做些什么来解决这个问题。
from tkinter import *
import tkinter.messagebox as tm
class LoginFrame(Frame):
def __init__(self, master):
super().__init__(master)
self.label_1 = Label(self, text="Username")
self.label_2 = Label(self, text="Password")
self.entry_1 = Entry(self)
self.entry_2 = Entry(self, show="*")
self.label_1.grid(row=0, sticky=E)
self.label_2.grid(row=1, sticky=E)
self.entry_1.grid(row=0, column=1)
self.entry_2.grid(row=1, column=1)
self.checkbox = Checkbutton(self, text="Keep me logged in")
self.checkbox.grid(columnspan=2)
***def destroy(self):
self.destroy()
self.logbtn = Button(self, text="Login", command = self._login_btn_clickked,)
self.logbtn.grid(columnspan=2)
self.pack()
def _login_btn_clickked(self):
username = self.entry_1.get()
password = self.entry_2.get()
if username == "jake" and password == "hey":
tm.showinfo("Login info", "Welcome Jake")
master=Tk()
def login2():
tm.showinfo("Logging in", "Logging In...")
b = Button(master, text="Enter GUI", command=login2)
b.pack()
else:
tm.showerror("Login error", "Incorrect username")***
root = Tk()
lf = LoginFrame(root)
root.mainloop()
答案 0 :(得分:1)
你永远不应该在程序中多次调用Tk()。如果您需要其他窗口,请使用Toplevel()。
但是,在您的情况下,您也不需要。你正在摧毁框架的正确轨道,现在你只需要启动一个新的框架。我们可以把这个逻辑放到Tk类中:
import tkinter as tk
class Mainframe(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.frame = FirstFrame(self)
self.frame.pack()
def change(self, frame):
self.frame.pack_forget() # delete currrent frame
self.frame = frame(self)
self.frame.pack() # make new frame
class FirstFrame(tk.Frame):
def __init__(self, master=None, **kwargs):
tk.Frame.__init__(self, master, **kwargs)
master.title("Enter password")
master.geometry("300x200")
self.status = tk.Label(self, fg='red')
self.status.pack()
lbl = tk.Label(self, text='Enter password')
lbl.pack()
self.pwd = tk.Entry(self, show="*")
self.pwd.pack()
self.pwd.focus()
self.pwd.bind('<Return>', self.check)
btn = tk.Button(self, text="Done", command=self.check)
btn.pack()
btn = tk.Button(self, text="Cancel", command=self.quit)
btn.pack()
def check(self, event=None):
if self.pwd.get() == 'password':
self.master.change(SecondFrame)
else:
self.status.config(text="wrong password")
class SecondFrame(tk.Frame):
def __init__(self, master=None, **kwargs):
tk.Frame.__init__(self, master, **kwargs)
master.title("Main application")
master.geometry("600x400")
lbl = tk.Label(self, text='You made it to the main application')
lbl.pack()
if __name__=="__main__":
app=Mainframe()
app.mainloop()