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

以下是代码的文件 struct :

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'

keywords.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.

Test.txt

kTest1
Test1
kTest2
Test2
kTest3
Test3
kTest4
Test4
kTest5
Test5
kTest6
Test6

推荐答案

代码:

这段代码对我来说运行得很好,尽管我注释掉了temp_list.append(temp[i+1].capitalize()),因为它导致了IndexOutOfRange错误:

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

information = []
file_name_old = 'keywords.txt'
file_name = './Text/'+file_name_old
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(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 = []
    current_dir = os.path.dirname(os.path.realpath(__file__))
    print(current_dir)
    
    text_dir = os.path.join(current_dir, "Text")
    if os.path.exists(text_dir):
        os.chdir(text_dir)
    else:
        os.chdir(current_dir)
    
    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 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()

树文件:

File Tree

证明:

Flash Card Project Proof

Python相关问答推荐

Python在tuple上操作不会通过整个单词匹配

Pydantic 2.7.0模型接受字符串日期时间或无

我从带有langchain的mongoDB中的vector serch获得一个空数组

删除任何仅包含字符(或不包含其他数字值的邮政编码)的观察

需要计算60,000个坐标之间的距离

在Pandas DataFrame操作中用链接替换'方法的更有效方法

优化pytorch函数以消除for循环

大小为M的第N位_计数(或人口计数)的公式

我对我应该做什么以及我如何做感到困惑'

移动条情节旁边的半小提琴情节在海运

计算分布的标准差

索引到 torch 张量,沿轴具有可变长度索引

polars:有效的方法来应用函数过滤列的字符串

判断Python操作:如何从字面上得到所有decorator ?

GPT python SDK引入了大量开销/错误超时

在极点中读取、扫描和接收有什么不同?

在聚合中使用python-polars时如何计算模式

普洛特利express 发布的人口普查数据失败

函数()参数';代码';必须是代码而不是字符串

组颠倒大Pandas 数据帧