我有一个tkinter GUI,用户需要在某个系统上进行身份验证 . 当用户单击RUN时,将弹出身份验证Toplevel,其中用户输入凭据,单击“确定”,应用程序将根据这些凭据创建连接实例 .
我遇到的困难是传回该连接实例,并且在成功返回之前没有继续执行应用程序 . 这是一个极其简化的代码片段,显示了总体布局 .
import tkinter as tk
def log_in():
def click_ok():
username = usr_entry_var.get()
password = pwd_entry_var.get()
# This is the portion that creates a connection instance
# that I desire to later perform actions against in the
# form of connection.doStuff()
# I have just set it to some text here for brevity, as this
# portion is working fine.
connection = 'someStuffThatAuthenticates'
login.destroy()
login = tk.Toplevel()
usr_lbl = tk.Label(login, text='Username:')
usr_lbl.grid(column=0, row=0)
usr_entry_var = tk.StringVar()
usr_entry = tk.Entry(login, width=40, textvariable=usr_entry_var)
usr_entry.grid(column=1, row=0)
pwd_lbl = tk.Label(login, text='Password:')
pwd_lbl.grid(column=0, row=1)
pwd_entry_var = tk.StringVar()
pwd_entry = tk.Entry(login, width=40, textvariable=pwd_entry_var)
pwd_entry.grid(column=1, row=1)
ok_btn = tk.Button(login, text='OK', command=click_ok)
ok_btn.grid(column=0, columnspan=2, row=2)
def click_run():
connection = log_in()
# Here is where I perform actions against the returned connection instance.
# I am just printing it here for brevity.
print(str(connection))
root = tk.Tk()
run_btn = tk.Button(root, text='RUN', command=click_run)
run_btn.pack()
root.mainloop()
我从上面得到的结果是,当我单击root上的RUN按钮时,代码 print()
s None同时登录屏幕弹出 . 我已经尝试了很多东西来获取代码
A)成功返回 connection
B)在尝试使用之前等待它返回
我没有列出我的微弱尝试,而是将代码简单地留在这里 . 谢谢你的建议!
1 回答
解决此问题的常用方法是使用tkinter的
wait_window
或wait_variable
方法 . 第一个将不会返回,直到目标窗口被销毁(典型的模态对话框),wait_variable
将不会返回,直到设置变量(非模态对话框常见)在程序等待的同时,它仍然能够处理事件 .
effbot.org对创建对话框进行了简明扼要的写作:http://effbot.org/tkinterbook/tkinter-dialog-windows.htm