我的 tkinter 应用程序不会更改正在加载的文件

问题描述 投票:0回答:1

我正在用 python 编写一个 tkinter 应用程序,它是一个闪卡测验。它需要能够从 python 文件前面一个文件夹的 txt 文件中读取数据。在 cide 中,您可以更改加载的文件是哪个文件,但即使您选择相同的文件,这也不起作用。当我尝试更改 filehandling() 中的文件时,它损坏了,但当它启动时,它工作了,我尝试使用它已经在使用的 keywords.txt 和 test.txt。

这是代码的文件结构:

This is the file structure of the code

from customtkinter import *
from CTkMessagebox import CTkMessagebox
import glob
import os

information = []
file_name = 'keywords.txt'
app = None


def hide(tk):
    # hides window
    try:
        tk.withdraw()
    except:
        pass


def show(tk):
    # shows window
    tk.deiconify()


def FileHandling(filename):
    # file handling
    information = []
    with open("Text/"+filename, 'r') as f:
        temp = f.read().split("\n")

    for i in range(0, len(temp), 2):
        temp_list = []
        # makes 2d array
        temp_list.append(temp[i].capitalize())
        temp_list.append(temp[i+1].capitalize())
        information.append(temp_list)
    return information


def changeHandler(value):
    global file_name
    file_name = value
    print(value)
    return file_name


def changeFile():
    # add change file code here
    files = getFiles()
    filePicker(files)


def getFiles():
    temp = []
    os.chdir("../Code/Text")
    for file in glob.glob("*.txt"):
        temp.append(file)
    return temp


def filePicker(files):
    hide(app)
    FilePicker = CTkToplevel()
    FilePicker.geometry("500x400")
    FilePicker.resizable(False, False)
    FilePicker.title("FIle Picker")
    Title = CTkLabel(
        master=FilePicker, text="Which file would you like to load?", font=("Arial", 10))
    Title.place(relx=0.5, rely=0.05, anchor="center")

    Options = CTkComboBox(FilePicker, values=files,
                          variable="Unselected", command=changeHandler)  # type: ignore
    Options.place(relx=0.5, rely=0.5, anchor="center")

    ExitBtn = CTkButton(master=FilePicker, text="Menu",
                        fg_color="#550000", text_color="#000000", command=lambda: Menu(FilePicker)).place(relx=0.5, rely=0.7, anchor="center")


def Menu(tk=None):
    global information
    information = FileHandling(file_name)
    global app
    # makes app unless app is made then it reveals it.
    if app == None:
        app = CTk()
        app.geometry("500x400+750+300")
        app.resizable(False, False)
        app.title("Menu")
        set_appearance_mode("dark")

        Title = CTkLabel(master=app, text="Flash Card Project",
                         font=("Arial", 40))
        PlayBtn = CTkButton(master=app, text="Start",
                            fg_color="#005500", text_color="#000000", command=lambda: Run(app))
        Changebtn = CTkButton(master=app, text="Change File",
                              fg_color="#AA4203", text_color="#000000", command=changeFile)
        ExitBtn = CTkButton(master=app, text="Exit",
                            fg_color="#550000", text_color="#000000", command=app.quit)

        Title.place(relx=0.5, rely=0.05, anchor="center")
        PlayBtn.place(relx=0.5, rely=0.4, anchor="center")
        Changebtn.place(relx=0.5, rely=0.5, anchor="center")
        ExitBtn.place(relx=0.5, rely=0.6, anchor="center")
        app.mainloop()
        exit()
    else:
        show(app)
        try:
            tk.destroy()
        except:
            pass


Menu()


keywords.txt
Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\lib\tkinter\__init__.py", line 1921, in __call__
    return self.func(*args)
  File "C:\Users\jacen\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\customtkinter\windows\widgets\ctk_button.py", line 554, in _clicked
    self._command()
  File "E:\Documents\Python Code\Flash Cards Project\Code\test.py", line 75, in <lambda>
    fg_color="#550000", text_color="#000000", command=lambda: Menu(FilePicker)).place(relx=0.5, rely=0.7, anchor="center")    
  File "E:\Documents\Python Code\Flash Cards Project\Code\test.py", line 80, in Menu
    information = FileHandling(file_name)
  File "E:\Documents\Python Code\Flash Cards Project\Code\test.py", line 27, in FileHandling
    with open("Text/"+filename, 'r') as f:
FileNotFoundError: [Errno 2] No such file or directory: 'Text/keywords.txt'
test.txt
Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\lib\tkinter\__init__.py", line 1921, in __call__
    return self.func(*args)
  File "C:\Users\jacen\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\customtkinter\windows\widgets\ctk_button.py", line 554, in _clicked
    self._command()
  File "E:\Documents\Python Code\Flash Cards Project\Code\test.py", line 75, in <lambda>
    fg_color="#550000", text_color="#000000", command=lambda: Menu(FilePicker)).place(relx=0.5, rely=0.7, anchor="center")    
  File "E:\Documents\Python Code\Flash Cards Project\Code\test.py", line 80, in Menu
    information = FileHandling(file_name)
  File "E:\Documents\Python Code\Flash Cards Project\Code\test.py", line 27, in FileHandling
    with open("Text/"+filename, 'r') as f:
FileNotFoundError: [Errno 2] No such file or directory: 'Text/test.txt'

关键词.txt

cellulose
Tough substance that makes up the cell walls of green plants.
respiration
A chemical reaction that causes energy to be released from glucose.
haemoglobin
A substance which joins to oxygen and carries it round the body in blood.
ventilation
Breathing.
cartilage
Tough and smooth substance covering the ends of bones to protect them.
cytoplasm
Jelly-like part of a cell where chemical reactions happen.
nucleus
Controls what happens inside a cell.
alveoli
Tiny air sacs in the lungs.
amino acids
Produced when proteins are digested.
virus
The smallest type of microbe.
white blood cells
Can engulf bacteria or make antibodies.
photosynthesis
The process of turning carbon dioxide water and light into glucose and oxygen.
stomata
Small holes in the underside of a leaf.
vaccine
Dead or inactive forms of a microorganism.
fibre
A nutrient that cannot be digested.

测试.txt

kTest1
Test1
kTest2
Test2
kTest3
Test3
kTest4
Test4
kTest5
Test5
kTest6
Test6
python python-3.x tkinter file-handling
1个回答
0
投票

代码:

这段代码对我来说工作得很好,尽管我注释掉了

temp_list.append(temp[i+1].capitalize())
,因为它导致了
IndexOutOfRange
错误:

from customtkinter import *
from CTkMessagebox import CTkMessagebox
import glob
import os

information = []
file_name = 'keywords.txt'
app = None


def hide(tk):
    # hides window
    try:
        tk.withdraw()
    except:
        pass


def show(tk):
    # shows window
    tk.deiconify()


def FileHandling(filename):
    # file handling
    information = []
    with open("./Text/"+filename, 'r') as f:
        temp = f.read().split("\n")

    for i in range(0, len(temp), 2):
        temp_list = []
        # makes 2d array
        temp_list.append(temp[i].capitalize())
        print(temp[i])
        # temp_list.append(temp[i+1].capitalize())
        information.append(temp_list)
    return information


def changeHandler(value):
    global file_name
    file_name = value
    print(value)
    return file_name


def changeFile():
    # add change file code here
    files = getFiles()
    filePicker(files)


def getFiles():
    temp = []
    os.chdir("../Code/Text")
    for file in glob.glob("*.txt"):
        temp.append(file)
    return temp


def filePicker(files):
    hide(app)
    FilePicker = CTkToplevel()
    FilePicker.geometry("500x400")
    FilePicker.resizable(False, False)
    FilePicker.title("File Picker")
    Title = CTkLabel(
        master=FilePicker, text="Which file would you like to load?", font=("Arial", 10))
    Title.place(relx=0.5, rely=0.05, anchor="center")

    Options = CTkComboBox(FilePicker, values=files,
                          variable="Unselected", command=changeHandler)  # type: ignore
    Options.place(relx=0.5, rely=0.5, anchor="center")

    ExitBtn = CTkButton(master=FilePicker, text="Menu",
                        fg_color="#550000", text_color="#000000", command=lambda: Menu(FilePicker)).place(relx=0.5, rely=0.7, anchor="center")


def Menu(tk=None):
    global information
    information = FileHandling(file_name)
    global app
    # makes app unless app is made then it reveals it.
    if app == None:
        app = CTk()
        app.geometry("500x400+750+300")
        app.resizable(False, False)
        app.title("Menu")
        set_appearance_mode("dark")

        Title = CTkLabel(master=app, text="Flash Card Project",
                         font=("Arial", 40))
        PlayBtn = CTkButton(master=app, text="Start",
                            fg_color="#005500", text_color="#000000", command=lambda: Run(app))
        Changebtn = CTkButton(master=app, text="Change File",
                              fg_color="#AA4203", text_color="#000000", command=changeFile)
        ExitBtn = CTkButton(master=app, text="Exit",
                            fg_color="#550000", text_color="#000000", command=app.quit)

        Title.place(relx=0.5, rely=0.05, anchor="center")
        PlayBtn.place(relx=0.5, rely=0.4, anchor="center")
        Changebtn.place(relx=0.5, rely=0.5, anchor="center")
        ExitBtn.place(relx=0.5, rely=0.6, anchor="center")
        app.mainloop()
        exit()
    else:
        show(app)
        try:
            tk.destroy()
        except:
            pass


Menu()

文件树:

证明:

© www.soinside.com 2019 - 2024. All rights reserved.