如何将函数转换为类?

2024-04-26 13:45:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为我的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")

Tags: 函数textselftxtboxaddtaskinput
1条回答
网友
1楼 · 发布于 2024-04-26 13:45:44

不清楚你的老师关于上课是什么意思。我猜他们希望您创建一个“todo list”对象,该对象具有添加和删除任务的方法。我不知道他们是否希望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甚至webapp甚至移动app中重用底层的todo列表逻辑。你知道吗

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)

相关问题 更多 >