[英]Returning from tkinter toplevel button click
我有一個tkinter GUI,用戶需要在其中對某些系統進行身份驗證。 當用戶單擊RUN時,將彈出身份驗證頂級,其中用戶輸入憑據,單擊確定,然后應用程序根據這些憑據創建連接實例。
我遇到的困難是傳回該連接實例,並且在成功返回應用程序之前無法繼續進行處理。 這是一個極其簡化的代碼片段,顯示了總體布局。
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)等到它返回后再嘗試使用它
我沒有列出我微不足道的嘗試,而只是將代碼簡化了一下。 感謝您的任何建議!
解決此問題的正常方法是使用wait_window
的wait_window
或wait_variable
方法。 在目標窗口被銷毀之前(典型的是模式對話框),第一個不會返回,而在設置了變量之前, wait_variable
將不會返回(與非模式對話框相同)
在程序等待時,它仍然能夠處理事件。
effbot.org關於創建對話框的文章非常簡潔: http ://effbot.org/tkinterbook/tkinter-dialog-windows.htm
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.