我有一个简单的gui(tkinter(程序,可以将数据写入文件。使用搁板。 当我想禁用该程序时,如何运行shelve.close((?
关闭无关紧要的事情的规范方法是使用上下文管理器:
with shelve.open(...) as myshelve:
# ALL YOUR CODE HERE
root.mainloop()
这保证了 shelve.close(( 将被调用,即使代码中出现任何异常也是如此。
这也是文档中推荐的方法:
不要依赖自动关闭的架子;当您不再需要它时,请始终显式调用
close()
,或者将shelve.open()
用作上下文管理器。
或者,由于您使用的是 tkinter,因此您可以使用WM_DELETE_WINDOW
事件:
import tkinter as tk
root = tk.Tk()
def when_window_is_closed():
myshelve.close()
root.destroy()
root.protocol("WM_DELETE_WINDOW", when_window_is_closed)
root.mainloop()
此方法更糟糕,因为它依赖于 tk 触发事件。请改用上下文管理器方法来涵盖所有理由。
当 GUI 停止时,mainloop
调用将停止。如果您想在 GUI 退出后运行一些代码,只需将其放在mainloop()
之后即可。
root.mainloop() # starts the GUI and waits for the GUI to close
shelve.close() # do something after the GUI closes