我正在创建一个客户列表,我正在使用字典和pickle来保存和存储客户名称和年龄。不幸的是,我的保存功能会覆盖任何现有用户,然后我的__init__
功能不会在字典中显示我自己输入的数据。此外,add
函数不会显示带有客户端名称的标签。能否帮助解决泡菜问题,因为我需要快速回答!
提前致谢!
from Tkinter import *
import pickle
root=Tk()
dic={}
class Launch(object):
def __init__(self, root):
root.withdraw()
root=Toplevel(root)
root.title("Choose Client")
self.row=3
for key in dic:
Label(root, text=key).grid(row=row, column=0)
self.row+=1
l3=Label(root, text="Client Name")
l3.grid(row=0, column=0)
self.e1=Entry(root)
self.e1.grid(row=0, column=1)
l4=Label(root, text="Client age")
l4.grid(row=1, column=0)
self.e2=Entry(root)
self.e2.grid(row=1, column=1)
b3=Button(root, text="Create client", command=self.add)
b3.grid(row=2)
def add(self):
client=self.e1.get()
age=self.e2.get()
dic[client]=age
Label(root, text="%s" % (client)).grid(row=self.row)
with open("data", "w") as f:
pickle.dump(dic, f)
def load(self):
dic=pickle.load(open("data", "rb"))
app=Launch(root)
root.mainloop()
答案 0 :(得分:0)
根本不使用load
方法。以下是修改后的代码,以使用load
。
from Tkinter import *
import pickle
root=Tk()
dic={}
class Launch(object):
def __init__(self, root):
self.load() # <-- load
root.title("Choose Client")
self.row = 3
for key in dic:
Label(root, text=key).grid(row=self.row, column=0)
self.row += 1
l3=Label(root, text="Client Name")
l3.grid(row=0, column=0)
self.e1=Entry(root)
self.e1.grid(row=0, column=1)
l4=Label(root, text="Client age")
l4.grid(row=1, column=0)
self.e2=Entry(root)
self.e2.grid(row=1, column=1)
b3=Button(root, text="Create client", command=self.add)
b3.grid(row=2)
def add(self):
client=self.e1.get()
age=self.e2.get()
dic[client]=age
Label(root, text=client).grid(row=self.row)
self.row += 1 # <--- increase row count
with open("data", "wb") as f:
pickle.dump(dic, f)
def load(self):
# should be declared, otherwise, will create local variable
global dic
try:
dic = pickle.load(open("data", "rb"))
except IOError: # if file does not exist.
pass
app = Launch(root)
root.mainloop()
以下是另一个使用实例变量而不是全局变量的版本:
from Tkinter import *
import pickle
class Launch(object):
def __init__(self, root):
self.load() # <-- load
root.title("Choose Client")
self.row = 3
for key in self.dic:
Label(root, text=key).grid(row=self.row, column=0)
self.row += 1
l3 = Label(root, text="Client Name")
l3.grid(row=0, column=0)
self.e1 = Entry(root)
self.e1.grid(row=0, column=1)
l4 = Label(root, text="Client age")
l4.grid(row=1, column=0)
self.e2 = Entry(root)
self.e2.grid(row=1, column=1)
b3 = Button(root, text="Create client", command=self.add)
b3.grid(row=2)
def add(self):
client = self.e1.get()
age = self.e2.get()
self.dic[client] = age
Label(root, text=client).grid(row=self.row)
self.row += 1 # <--- increase row count
with open("data", "wb") as f:
pickle.dump(self.dic, f)
def load(self):
try:
self.dic = pickle.load(open("data", "rb"))
except IOError:
self.dic = {}
root = Tk()
app = Launch(root)
root.mainloop()