我正在为我的uni(GUI程序)编写课程,但是由于我的代码正常工作,我遇到了一个问题,但是规范是我们使用OOP而不是函数,所以我迷路了。
我尝试为每个按钮创建新的类,但是我不知道如何使它们像在函数中那样工作。
def add():
#get input
task=txt_input.get()
if task !="":
tasks.append(task)
#updating the list box
update_listbox()
else:
display["text"]=("Input a task.")
with open("ToDoList.txt", "a") as f:
f.write(task)
f.close()
txt_input=tk.Entry(root, width=25)
txt_input.pack(pady=15)
add=tk.Button(root, text="Add", fg="DarkOrchid3", bg="blanched almond", command=add)
add.pack(pady=5, ipadx=15)
这允许用户将任务添加到GUI中的任务列表中,但是就像我说的那样,应该使用OOP而不是功能。 如果我了解这一点,则应该可以完成其余的按钮。
更新: 好的,所以我尝试了下面给出的解决方案,但我真的不知道我的代码有什么问题,GUI出现了,但是添加功能不起作用。
class ToDoList():
def __init__(self):
self.tasks = []
def update_listbox(self):
#calling clear function to clear the list to make sure tasks don't keep on adding up
clear()
for task in self.tasks:
box_tasks.insert("end", task)
def clear(self):
box_tasks.insert("end", task)
class adding():
def add(self):
task=txt_input.get()
if task!="":
self.tasks.append(task)
update_listbox()
else:
display["text"]=("Input a task")
答案 0 :(得分:1)
不清楚您的老师对使用课堂的意义。我猜想他们希望您创建一个“待办事项列表”对象,该对象具有添加和删除任务的方法。我不知道他们是否希望GUI成为该类的一部分。可能是您的整个应用程序都是由类组成的,或者您只能将类用于业务逻辑。
我认为您应该首先为业务逻辑创建一个类。看起来像这样:
class ToDoList():
def __init__(self):
self.the_list = []
def add(self, value):
<code to add the value to self.the_list>
def remove(self, item):
<code to remove a value from self.the_list>
有了它,您可以编写一个没有GUI的简单小程序,从而可以轻松测试逻辑:
# create an instance of the to-do list
todo_list = ToDoList()
# add two items:
todo_list.add("mow the lawn")
todo_list.add("buy groceries")
# delete the first item:
todo_list.remove(0)
要在此基础上构建GUI,可以将GUI组件添加到现有类中,也可以创建专门用于该GUI的新类。每个都有优点和缺点。
在下面的示例中,GUI是一个单独的类,它使用ToDoList
类来维护数据。这种设计使您可以在测试,GUI甚至Web应用程序甚至移动应用程序中重用底层的待办事项列表逻辑。
class ToDoGUI():
def __init__(self):
# initalize the list
self.todo_list = ToDoList()
# initialize the GUI
<code to create the entry, button, and widget to show the list>
def add(self):
# this should be called by your button to the list
data = self.entry.get()
self.todo_list.add(data)