I am designing a program and i want it to autosave when the root window gets closed by the user. I already created the function, but its not neccesary. How do i bind a function to the window close event?
Example code:
import sys
import tkinter as tk
import tkinter.ttk as ttk
from tkinter.constants import *
def main(*args):
global root
root = tk.Tk()
root.protocol('WM_DELETE_WINDOW', root.destroy)
global _top2, _w2
_top2 = root
_w2 = spiel(_top2)
root.mainloop()
class spiel:
def __init__(self, top=None):
_bgcolor = '#d9d9d9' # X11 color: 'gray85'
_fgcolor = '#000000' # X11 color: 'black'
_compcolor = '#d9d9d9' # X11 color: 'gray85'
_ana1color = '#d9d9d9' # X11 color: 'gray85'
_ana2color = '#ececec' # Closest X11 color: 'gray92'
self.style = ttk.Style()
if sys.platform == "win32":
self.style.theme_use('winnative')
self.style.configure('.',background=_bgcolor)
self.style.configure('.',foreground=_fgcolor)
self.style.map('.',background=
[('selected', _compcolor), ('active',_ana2color)])
top.geometry("600x450 475 21")
top.minsize(600, 450)
top.maxsize(600, 450)
top.resizable(0,0)
top.title("mathe")
top.configure(background="#d9d9d9")
top.configure(highlightbackground="#d9d9d9")
top.configure(highlightcolor="black")
self.top = top
self.Frame1 = tk.Frame(self.top)
self.Frame1.place(relx=0.017, rely=0.133, relheight=0.856
, relwidth=0.975)
def function():
print(fr"This function shall be exectuted when the user closes the window.")
if __name__ == '__main__':
main()
Info: I do not want to block the close button and create my own version using root.quit(), i want the user to have the normal close button.
If you know how to do this, please tell me, Thank you :)
CodePudding user response:
You should use function
instead of root.destroy
in root.protocol('WM_DELETE_WINDOW', ...)
and call root.destroy()
at the end of function()
:
...
def function():
print(fr"This function shall be exectuted when the user closes the window.")
root.destroy()
def main(*args):
global root
root = tk.Tk()
root.protocol('WM_DELETE_WINDOW', function) # call function() when window is closed
global _top2, _w2
_top2 = root
_w2 = spiel(_top2)
root.mainloop()
...