Python 用Tkinter实现密码对话框
我正在尝试实现一个获取用户密码的对话框。我创建了类Python 用Tkinter实现密码对话框,python,user-interface,tkinter,tk,Python,User Interface,Tkinter,Tk,我正在尝试实现一个获取用户密码的对话框。我创建了类PasswordDiaglog,该类继承自tk.Toplevel,但这会导致问题,即它的执行是父帧的非阻塞 import Tkinter as tk class PasswordDialog(tk.Toplevel): def __init__(self, parent): tk.Toplevel.__init__(self) self.password = None self.entry
PasswordDiaglog
,该类继承自tk.Toplevel
,但这会导致问题,即它的执行是父帧的非阻塞
import Tkinter as tk
class PasswordDialog(tk.Toplevel):
def __init__(self, parent):
tk.Toplevel.__init__(self)
self.password = None
self.entry = tk.Entry(self, show='*')
self.entry.pack()
self.button = tk.Button(self)
self.button["text"] = "Submit"
self.button["command"] = self.StorePass
self.button.pack()
def StorePass(self):
self.password = self.entry.get()
self.destroy()
print '1: Password was', self.password
class MainApplication(tk.Frame):
def __init__(self, root):
tk.Frame.__init__(self, root)
self.button = tk.Button(self)
self.button["text"] = "Password"
self.button["command"] = self.GetPassword
self.button.pack()
def GetPassword(self):
passwd = PasswordDialog(self)
# HALT HERE
print '2: Password was', passwd.password
if __name__ == "__main__":
root = tk.Tk()
MainApplication(root).pack(side="top", fill="both", expand=True)
root.mainloop()
通过将my code a作为密码运行,可以在终端中看到以下输出:
2: Password was None
1: Password was foobar
预期产出应为:
1: Password was foobar
2: Password was foobar
关于如何解决这个问题,或者如何实现密码对话框,您有什么想法吗
在输入
条目后点击回车键调用StoredPass()
,将密码存储为MainAplication
类的属性,并使用传入的parent
作为PasswordDialog
类的句柄,这意味着您可以使用self.wait\u窗口(PasswordDialog(self))
要阻止执行,直到销毁PasswordDialog
:
import Tkinter as tk
class PasswordDialog(tk.Toplevel):
def __init__(self, parent):
tk.Toplevel.__init__(self)
self.parent = parent
self.entry = tk.Entry(self, show='*')
self.entry.bind("<KeyRelease-Return>", self.StorePassEvent)
self.entry.pack()
self.button = tk.Button(self)
self.button["text"] = "Submit"
self.button["command"] = self.StorePass
self.button.pack()
def StorePassEvent(self, event):
self.StorePass()
def StorePass(self):
self.parent.password = self.entry.get()
self.destroy()
print '1: Password was', self.parent.password
class MainApplication(tk.Frame):
def __init__(self, root):
tk.Frame.__init__(self, root)
self.password = None
self.button = tk.Button(self)
self.button["text"] = "Password"
self.button["command"] = self.GetPassword
self.button.pack()
def GetPassword(self):
self.wait_window(PasswordDialog(self))
print '2: Password was', self.password
if __name__ == "__main__":
root = tk.Tk()
MainApplication(root).pack(side="top", fill="both", expand=True)
root.mainloop()
要绑定返回键,可以使用:
self.entry.bind("<KeyRelease-Return>", self.StorePassEvent)
您也可以改用lambda
:
self.entry.bind("<KeyRelease-Return>", lambda x: self.StorePass())
self.entry.bind(“,lambda x:self.StorePass())
def StorePassEvent(self, event):
self.StorePass()
self.entry.bind("<KeyRelease-Return>", lambda x: self.StorePass())