Bas*_*asj 3 python xml serialization json tkinter
我创建了tkinter希望保存在JSON或XML文件中的对象(使用小部件),以便我可以在启动后恢复它们.
from Tkinter import *
class Texte:
def __init__(self, ax, ay, txt):
self.entry = Entry(root,bd=0,font=("Purisa",int(15)))
self.entry.insert(0, txt)
self.x = ax
self.y = ay
self.entry.place(x=self.x,y=self.y)
root = Tk()
a = Texte(10, 20, 'blah')
b = Texte(20, 70, 'blah2')
# here the user will modify the entries' x, y, txt, etc.
L = [a,b]
# here save the list L (containing the Texte objects) into a JSON file or XML so that I can recover them after restart
root.mainloop()
Run Code Online (Sandbox Code Playgroud)
如何使用JSON或XML保存和恢复这些对象?
它在文档中提到,使用json.dump.
使用示例:
import json
data = {'a':1, 'b':2}
with open('my_json.txt', 'w') as fp:
json.dump(data, fp)
Run Code Online (Sandbox Code Playgroud)
在您的情况下,您不能将对象本身转换为json格式.仅保存信息:
data = {'a':(10, 20, 'blah'), 'b':(20, 70, 'blah2')
with open('my_json.txt', 'w') as fp:
json.dump(data, fp)
Run Code Online (Sandbox Code Playgroud)
当你加载它时:
with open('my_json.txt') as fp:
data = json.loads(fp)
a = Texte(*data['a'])
b = Texte(*data['b'])
Run Code Online (Sandbox Code Playgroud)