简体   繁体   English

无法从其小部件的回调内部销毁 Tk 对象

[英]Unable to destroy a Tk object from inside its widget's callback

[Edited] I am trying to destroy a Toplevel object from inside its widget's callback, but it seems that it cannot be destroyed until the callback function is done running. [已编辑] 我试图从其小部件的回调内部销毁 Toplevel 对象,但似乎在回调函数运行完成之前无法销毁它。 Below is the essence of my script:以下是我的脚本的精髓:

from tkinter import *
from time import sleep
import gnupg
w = Tk()
t = Toplevel()
lbl = Label(t, text="blah blah")
lbl.grid(row=0, column=0)
lbl.bind("<Button-1>", func_a)

def func_a(event):
   event.widget.master.destroy()
   gpg = gnupg.GPG()
   plaindata = b'Some data'
   encrdata = plaindata
   for i in range(20):
      encrdata = gpg.encrypt(encrdata,
         symmetric=True,
         passphrase='something', 
         recipients=None).data
   print("func_a is done")
w.mainloop()

As you can see, I am using a gpg symmetric encryption 20 times, which takes ~20 seconds.如您所见,我使用了 20 次 gpg 对称加密,大约需要 20 秒。 What I expected to see when clicking on Label (object "lbl") is the entire Toplevel window (object "t") immediately disappearing and then 20 seconds later message "func_a is gone" being printed in the terminal.当单击 Label(对象“lbl”)时,我期望看到的是整个顶层窗口(对象“t”)立即消失,然后 20 秒后在终端中打印消息“func_a 消失”。 Instead, Toplevel window became unresponsive for 20 seconds (I could still move it but all of its widgets kinda froze) before finally disappearing the same time the aforementioned message was printed.相反,Toplevel 窗口在 20 秒内没有响应(我仍然可以移动它,但它的所有小部件都被冻结了),然后在打印上述消息的同时最终消失。

Could you please explain why the parent Toplevel did not get destroyed immediately?你能解释一下为什么父 Toplevel 没有立即被销毁吗? Does it have to do with the function being called as a widget's callback?它与作为小部件回调调用的函数有关吗? And how can I force the parent window to be killed before other content in the callback function is completed?以及如何在回调函数中的其他内容完成之前强制杀死父窗口?

OK, thanks to @martineau's pointers, I found a solution -- a very easy one at that.好的,感谢@martineau 的指点,我找到了一个解决方案——一个非常简单的解决方案。 I just invoked method update() from the Toplevel object whenever I wanted any changes to this object to take effect.每当我希望对该对象的任何更改生效时,我都只是从 Toplevel 对象调用方法update() This worked even if the preceding change was destroying this very object.即使前面的更改正在破坏这个对象,这也有效。 Thanks to all who provided their comments and feedback.感谢所有提供评论和反馈的人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM