python中tk的simpledialog.askstring报错解决方案

发布时间 2023-07-15 12:30:02作者: 顺其自然,道法自然

simpledialog.askstring还是比较好用的, 能够很方便的获取用户输入的文本, 但是在多线程中会出现下面的错误:
_tkinter.TclError: window ".!_querystring" was deleted before its visibility changed
解决的方案参考: https://stackoverflow.com/questions/53480400/tkinter-askstring-deleted-before-its-visibility-changed
我在代码中增加了中文注释:

#Create a new temporary "parent"
newWin = Tk()	# 创建一个新顶级窗口
#But make it invisible
newWin.withdraw()	# 使此窗口处于隐藏状态
#Now this works without throwing an exception:
retVal = simpledialog.askstring("Enter Value","Please enter a value",parent=newWin)	# 设置父窗口
print(f'用户的输入为:{retVal}')
#Destroy the temporary "parent"
newWin.destroy()	# 再销毁刚才创建的临时主窗口