将密码存储为属性MainAplication
类并使用传入的parent
作为手柄PasswordDialog
类意味着你可以使用self.wait_window(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()
现在的输出符合预期:
1: Password was foobar
2: Password was foobar
要绑定 Return 键,您可以使用:
self.entry.bind("<KeyRelease-Return>", self.StorePassEvent)
使用包装函数:
def StorePassEvent(self, event):
self.StorePass()
您还可以使用lambda
反而:
self.entry.bind("<KeyRelease-Return>", lambda x: self.StorePass())