Python 3 个保存按钮

Python 3 Save Buttons

我有一个可以创建另一个按钮的按钮,但是当我关闭程序时,我刚刚创建的按钮消失了。

我知道如何使用 pickle 将内容保存在文件中,但我应该如何编写代码才能保存按钮并在我打开程序时再次创建它们。

代码:

def CreateButton():
    global name,clicked,started
    started=True
    name = str(input("Write a Student Name..."))
    print('variable changed...')
    clicked=True

def update():
    global MainWindow,changed,clicked,name
    #global clicked
    if clicked and started:
        #name = input("Write a Student Name: ")
        button_new=needed_but(MainWindow=MainWindow,color="#E6E6E6",text=name)
        clicked=False
        buttonred=False
    MainWindow.after(1*1000,update)

class needed_but:
    def __init__(self,MainWindow,color,text):
        console = Button(MainWindow, text=text,bg=color, command=self.changecolor)
        console.pack()
        self.instance=console

    def changecolor(self):
        buttonred,buttongreen,buttonblue=get_color()
        global clicked,misses_dict
        #clicked=True
        #global buttoncolor
        if buttonred == True:
            self.instance.configure(bg = "#ff0000")
            dun = self.instance.cget('text')
            print(dun)
            if dun in misses_dict:
                misses_dict[('%s' %(dun))] += 1
            else:
                misses_dict[('%s' %(dun))] = 1
            pickle.dump(dictionary, open("%s\SI\SIA.dat" %(path), 'wb'))
            print(misses_dict)
            buttonred = False
        elif buttongreen == True:
            self.instance.configure(bg = "#00ff00")
        elif buttonblue == True:
            self.instance.configure(bg = "#2e9afe")

how should I write the code so that it saves the buttons and creates them again when I open the program.

你不能。这些对象实际上是嵌入式 tcl 解释器中的对象。无法保存解释器的状态。

您必须编写代码以某种格式保存有关小部件的所有信息,您可以在其中读回并重新创建小部件。