使用pickle和tkinter保存数据供以后使用

时间:2015-12-11 11:22:05

标签: python tkinter pickle

这是我的代码:

import pickle
from tkinter import *
from tkinter.messagebox import *

Game = Tk()

Gold = 0
Multiply = 1

def Save():
    with open('objs.pickle', 'wb') as f:
        pickle.dump([Gold, Multiply], f)

def Load():
    with open('objs.pickle', 'rb') as f:
        return pickle.load(f)

def ClickButton():
    global Gold
    print(Gold)
    Gold +=1 * (Multiply)



Load()
GoldButton = Button(Game, height = 15, width = 25, text="Click!", command ClickButton, bg = "purple")
GoldButton.place(x = 160, y = 95)


save = Button(Game, height = 15, width = 25, text="Click to Save", command = Save)
save.place(x = 380, y = 95)


Game.resizable(width=False, height = False)
Game.geometry('700x450')
Game.title("Gold Farm")

我想要它做什么:

  • 从Pickle文件中加载变量“Gold”和“Multiply”
  • 将新信息保存到文件apon闭包(Gold and Multiply)

问题在于,当我用文件中的变量重新打开程序时,它只是将Gold和Multiply设置为默认值

问题出在这里?我该如何解决?

1 个答案:

答案 0 :(得分:1)

您丢弃了正在加载的数据。 Load函数不会将数据保存到变量中,它只返回已加载的内容。

您需要保存从Load获得的值:

try:
    Gold, Multiply = Load()
except IOError:
    Gold, Multiply = 0, 1