Python, Tkinter - 退出gui程序时如何运行 'shelve.close ()'?

Python, Tkinter - How to run 'shelve.close ()' when exiting the gui program?

我有一个简单的 gui(tkinter) 程序,可以将数据写入文件。使用搁板。 如何在运行shelve.close()时禁用程序?

关闭某些东西的规范方法不管发生什么是使用上下文管理器:

with shelve.open(...) as myshelve:
    # ALL YOUR CODE HERE
    root.mainloop()

这保证 shelve.close() 将被调用,即使您在代码中遇到任何异常。

也是recommended way in the documentation:

Do not rely on the shelf being closed automatically; always call close() explicitly when you don’t need it any more, or use shelve.open() as a context manager.

或者,由于您使用的是 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