在独立应用程序中访问并行文件夹的文件

Accessing parallel folder's file in a standalone application

我使用 pyinstaller 创建了一个独立的 .app 应用程序 (ToDoList.py / ToDoList.app / ToDoList (Unix Executable))。我的代码使用一个名为 List.tx 的文件来记住和存储显示在屏幕上的数据。没有文件,程序不能运行。我在将文件放入捆绑包时遇到了问题,但最近我深入研究了 .app,发现当我使用“pyinstaller ToDoList.py --add-data 时它添加了 List.txt 文件“List.txt:.”--窗口化”。 List.txt 文件放在与 unix 可执行文件平行的资源文件夹中,现在我需要找到一种方法来使用我的程序访问它。我将附上屏幕截图和我的代码。如果有人可以提供帮助,将不胜感激!

我的代码:

import tkinter as tk
from tkinter import *
open = open("List.txt", "r+")
file = open.readlines ()
def main ():
    window = Tk()
    window.title("To Do")
    def window_destroy ():
        window.destroy()
    window.geometry ("1440x808+0+0")
    to_do_label = Label(window, text="To Do List:", font=("Times New Roman",25,))
    to_do_label.place(relx=.5, y=20, anchor=CENTER)
    to_do_listbox = Listbox(window, width=50, height=20)
    for i in range(len(file)):
        to_do_listbox.insert(tk.END, str(file[i].strip()))
    to_do_listbox.place(relx=.5, y=230, anchor=CENTER)
    def delete_selected_item ():
        to_do_listbox.delete(tk.ANCHOR)
        for i in range(to_do_listbox.size()):
            open.truncate(i)
        for i in range(to_do_listbox.size()):
            open.write(to_do_listbox.get(i) + "\n")
    add_entry = Entry(window, width=50, font=("Times New Roman", 15))
    add_entry.place(relx=.5, y=425, anchor=CENTER)
    def add_entry_to_list ():
        to_do_listbox.insert(tk.END, add_entry.get())
        for i in range(to_do_listbox.size()):
            open.truncate(i)
        for i in range(to_do_listbox.size()):
            open.write(to_do_listbox.get(i) + "\n")
    add_button = Button(window, text="Add item", width=10, font=("Times New Roman", 15), command=add_entry_to_list)
    add_button.place(relx=.5, y=455, anchor=CENTER)
    delete_button = Button(window, text="Delete item", width=10, font=("Times New Roman", 15), command=delete_selected_item)
    delete_button.place(relx=.5, y=485, anchor=CENTER)
    quit_button = Button(window, text = "Quit", width=5, font=("Times New Roman",15), command=window_destroy)
    quit_button.pack(anchor = "s", side = "right")
    window.mainloop()
main ()

Folder photo

您应该能够使用这样的代码打开您的文件:

import sys
from pathlib import Path
...
if getattr(sys, 'frozen', False):
    folder = Path(sys._MEIPASS)
else:
    folder = Path(__file__).parent
open = open(folder / "List.txt", "r+")