我创建了两个python文件 - 第一个存储主类,第二个用于GUI,它使用第一个的函数。我还有一个文件 - 我想要使用的项目列表 - 每次在GUI窗口中添加或删除项目时自动保存更改。我有一个问题,如何写下GUI的两个函数 - “add_item”和“delete_item”。当GUI窗口打开时,Add_item已经能够add_item,但是,它只是临时的,因为它不会保存对文件(项目列表)的更改。我是python的初学者,非常感谢任何帮助。
这是第一个py文件(存储类)的一部分:
def AddItem(self, item):
if isinstance(item, Item):
if item not in self:
self.append(item)
else:
raise ValueError("Item is in class already")
else:
raise ValueError("Object from class Item is expected")
def AddItemWithName(self, name, size, price):
newItem = Item(name, size, price)
self.add_item(newItem)
def DeleteItem(self, item):
if isinstance(item, Item):
if item in self:
self.remove(item)
else:
raise ValueError("Item was not deleted")
else:
raise ValueError("Object from class Item is expected")
def DeleteItemWithName(self, name):
self.delete_tiem(Item(name))
def SaveToFile(self):
with open("list_of_items.bin", 'bw') as f:
pickle.dump(self, f)
def LoadFromFile(self):
with open("list_of_items.bin", 'rb') as f:
self.clear()
self.extend(pickle.load(f))
这是GUI的第二个py文件的问题部分:
def add_item():
try:
name = input_value1.get()
size = input_value2.get()
price = input_value3.get()
items_class.addItemWithAtributes(name, size, price)
output_value1.set("Item was added")
except ValueError:
output_value1.set("Item was not added")
items_class.SaveToFile()
def delete_item():
try:
name = input_value4.get()
#items_class.deleteItemWithAtributes(name)
output_value1.set("Item was deleted")
except ValueError:
output_value1.set("Item was not deleted")
items_class.SaveToFile()