Search code examples
pythonpython-3.xtkinterfile-handling

My tkinter app wont change the file it is loading


I am writing a tkinter app in python that is a flash card quiz. It needs to be able to read from a txt file one folder ahead from the python file. In the cide you can change which file is the file loaded but this is not working even if you choose the same file. When i tried to change the file in filehandling() it broke but when it launched it worked I tried it with keywords.txt which it was already using and test.txt.

This is the file structure of the code:

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

Solution

  • Code:

    This code is working fine for me, although I commented out temp_list.append(temp[i+1].capitalize()) as its causing IndexOutOfRange error:

    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:

    File Tree

    Proof:

    Flash Card Project Proof