【问题标题】:Saving data with pickle and tkinter for later use使用 pickle 和 tkinter 保存数据以备后用
【发布时间】:2015-12-11 11:22:04
【问题描述】:

这是我的代码:

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”
  • 将新信息保存到关闭后的文件中(Gold 和 Multiply)

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

这里有什么问题?我该如何解决?

【问题讨论】:

    标签: python tkinter pickle


    【解决方案1】:

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

    你需要保存从Load返回的值:

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

    【讨论】:

    • 谢谢,这行得通。 :) 但是我还有一个问题,当文件不存在或文件为空时会出现错误,我该如何防止这种情况?
    • @Csarg os.path.isfile(file)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-23
    • 2011-05-30
    • 2019-02-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多