Question

I have a loop in Tkinter:

def main():
    #Global Variables
    windows = []
    buttons = []
    labels = []
    messageboxes = []
    global theme
    theme = 0
    listboxes = []
    global register
    register = []
    global path
    path = ""
    # Lotsa' Code
    Tkinter.mainloop()

if __name__ == "__main__":
    main()

def save_f():
    global register
    outFile = open('FobbySave.txt', 'wb')
    pickle.dump(register, outFile)
    outFile.close()
global register     
#At Quit
atexit.register(save_f)

atexit fails. But when I try to print register it has no problem. save_f worked when I put it in the Tkinter loop, but atexit didn't. So can somebody tell me what am I doing wrong?

P.S.

Sorry forgot to write atexit the first time. But it's in my code.

Edit: Orginal code down here

import pickle
import atexit
def save_f():
    global register
    outFile = open('Something.txt', 'wb')
    pickle.dump(register, outFile)
    outFile.close()
atexit.register(save_f)
Was it helpful?

Solution

OK turns out the problem was that I needed atexit.register(save_f) instead of atexit.register(save_f()).

You're not supposed to make a function call!

OTHER TIPS

Looking at your code I would suggest to try this instead:

def main():
    # ... everything in main ...
    Tkinter.mainloop()

def save_f():
    outFile = open('FobbySave.txt', 'wb')
    pickle.dump(register, outFile)
    outFile.close()

#At Quit
atexit.register(save_f)

if __name__ == "__main__":
    main()

The problem might have been that you initialize your atexit after you run the main method. So after the code gets killed (and stops executing) you try to add the atexit method.

Your basic script works for me, provided I import atexit and set register to something. e.g.:

import pickle
import atexit

def save_f():
    outFile = open('Something.txt', 'wb')
    pickle.dump(register, outFile)
    outFile.close()

register = 1
atexit.register(save_f)

(note that global isn't necessary either). In cases such as this, you should make sure that you don't have another file named atexit.py in the current directory or somewhere else on your PYTHONPATH ...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top