当您关闭(销毁)窗口时,它也会删除(销毁)Entry
(和其他小部件),当您尝试使用Entry
. Entry
您必须在关闭(销毁)窗口之前获取文本。
或者
因为您使用StringVar
in所以即使在关闭(销毁)窗口后Entry
也可以从中获取此文本。StringVar
显示此问题和解决方案的最小工作示例。
import tkinter as tk
# --- functions ---
def on_click():
global result
result = entry.get()
print('[before] result :', result) # OK - before destroying window
print('[before] StringVar:', msg.get()) # OK - before destroying window
print('[before] Entry :', entry.get()) # OK - before destroying window
root.destroy()
# --- main ---
result = "" # variable for text from `Entry`
root = tk.Tk()
msg = tk.StringVar(root)
entry = tk.Entry(root, textvariable=msg)
entry.pack()
button = tk.Button(root, text='Close', command=on_click)
button.pack()
root.mainloop()
# --- after closing window ---
print('[after] result :', result) # OK - after destroying window
print('[after] StringVar:', msg.get()) # OK - after destroying window
print('[after] Entry :', entry.get()) # ERROR - after destroying window