首页 > 解决方案 > 如何在另一个python文件中的列表中附加一些东西?

问题描述

我正在使用管理任务的 tkinter 制作任务 GUI,但是为了保存任务,我要做的是将所有任务附加到列表中,但问题是该列表位于另一个 python 文件中。所以,我想知道如何在另一个 python 文件中的列表中附加项目。并保存它

主文件名——main.py 另一个文件名——manage.py

main.py 中的内容

from tkinter import *
from tkinter import ttk
import manage


def saved_work():
    for item in manage.tasks:
        tasks_box1.insert(END, item)
        
        
def add_task_func():
    manage.tasks.append(add_task_entry.get())  # Not Working!! - Maybe coz the work is not saving:((
    
root = Tk()
root.title("Tasks")
root.geometry("500x500")
root.resizable(False, False)

start_up_image = PhotoImage(file="image1.png")

set_frame1 = Frame(root)
set_frame1.pack()

main_heading_image = Label(set_frame1, image=start_up_image)
main_heading_image.pack(side=LEFT)


heading = Label(set_frame1, text="Tasks", font=("Calibri", 40))
heading.pack(side=LEFT)

heading2 = Label(root, text="GUI For Managing your day to day Tasks!", font=("Calibri", 15))
heading2.pack()

ttk_notebook_tab = ttk.Notebook(root)
ttk_notebook_tab.pack(pady=5)

Tasks = Frame(ttk_notebook_tab, width=480, height=480)
important = Frame(ttk_notebook_tab, width=480, height=480)

Tasks.pack(fill="both", expand=1)
important.pack(fill="both", expand=1)

ttk_notebook_tab.add(Tasks, text="Tasks To Do")
ttk_notebook_tab.add(important, text="Importants")

tasks_box1 = Listbox(Tasks, width=70)
tasks_box1.pack(pady=15)

set_frame2 = Frame(Tasks)
set_frame2.pack()

add_task_entry = ttk.Entry(set_frame2, font=("Calibri", 13), width=32)
add_task_entry.pack(side=LEFT, padx=10)

add_task_btn1 = ttk.Button(set_frame2, text="Add Task", width=20, command=add_task_func)
add_task_btn1.pack()

set_frame3 = Frame(Tasks)
set_frame3.pack(pady=15)

remove_all = ttk.Button(set_frame3, text="Remove All Tasks", width=60)
remove_all.pack(pady=3)

remove_selected = ttk.Button(set_frame3, text="Remove Selected Tasks", width=60)
remove_selected.pack()

move_selected_to_importants = ttk.Button(set_frame3, text="Move Selected to Importants", width=60)
move_selected_to_importants.pack(pady=3)

# Widgets in Importants

importants_tasks_box = Listbox(important, width=70)
importants_tasks_box.pack(pady=15)

set_frame4 = Frame(important)
set_frame4.pack(pady=15)

remove_all = ttk.Button(set_frame4, text="Remove All Tasks", width=60)
remove_all.pack(pady=3)

remove_selected = ttk.Button(set_frame4, text="Remove Selected Tasks", width=60)
remove_selected.pack()

saved_work()
root.mainloop()

manage.py 中的内容

tasks = []

如果不可能,请告诉一个更好的方法:,(

标签: pythontkintersave

解决方案


在这种情况下,您应该将另一个文件作为模块导入

因此,在您manage.py的列表所在的位置,您将拥有

SOME_LIST=[1, 2, 3]

您应该在该文件夹中创建一个__init__.py文件,以确保您可以将其用作模块。

然后在要使用该列表的文件中:

from manage import SOME_LIST

[your code]

请注意,如果 manage.py 文件位于另一个目录中,则需要指定其所在位置的完整路径

from path.manage import SOME_LIST

您可以将该文件中的列表用作常量,但永久修改它是另一回事。如果要读取和写入数据,则需要使用某种文件而不是 Python 模块。也许是 JSON 或 YAML。如果列表很简单,甚至可能是一个 txt 文件,其中每一行都是列表的一个元素。


推荐阅读