1

I'm trying to understand how pickle work. So thanks to this answer here:Use pickle to load a state for class I start to understand how to store thing. But I'm kinda stuck in the next move. What I want to do is once I click the save button, it will display a button with the value on it, and once I click the button it will set the current value into the value on the button. And next time when I run the program again, I want my button still be there. I guess what I need to do is pickling the buttons so it can dumps back, but buttons are tkinter object right? how can I store them and load them into pickle?

import tkinter as tk
import pickle

class State:
    def __init__(self):
        self.val = 0


class start(tk.Frame):
    LOADERBUTTONS = []
    def __init__(self,*args,**kwargs):
        tk.Frame.__init__(self,*args,**kwargs)
        frame = tk.Frame(self,width=600,height=600)
        self.state = State()
        self.plusButton = tk.Button(self,text="plus",command=self.plus)
        self.plusButton.pack()
        self.valLabel1 = tk.Label(self)
        self.valLabel1.pack()
        self.saveButton = tk.Button(self,text="save",command=self.save)
        self.saveButton.pack()
        self.loadButton = tk.Button(self,text="load",command=self.load)
        self.loadButton.pack()
    def load(self):
        self.state = pickle.load(open( "testtesttest.p", "rb" ))
        self.valLabel1.config(text="%d"%(self.state.val))
    def plus(self):
        self.state.val += 1 
        self.valLabel1.config(text="%d"%(self.state.val))

    def save(self):
        pickle.dump(self.state, open( "testtesttest.p", "wb" ))
        self.valButtonLoader = tk.Button(self,text="%d"%(hash(self.state.val))).pack()
        start.LOADERBUTTONS.append(tk.Button(self.valButtonLoader))

 if __name__=='__main__':
   root = tk.Tk()

   start(root).pack()
   root.mainloop()

Apparently I'm trying to use class attribute to save all the buttons I have, but this seems to be a dead end. Any idea?

Thanks a lot.

Community
  • 1
  • 1
angieShroom
  • 133
  • 3
  • 9

0 Answers0