0

I have been trying to develop a GUI for my python based voice assistant. The following is a snippet of the code that I am having problem with.
What I want to do is display the name of text files from a folder and display their contents in the same window when the user clicks on one of the file names.

from tkinter import *
import os

menu_color = "#2c2b34"
frame_color = "#28262e"
font_color = "#06dff5"

ss_f_button = []
note_f_button = []
note_text = None

def note_window():  #To operate Note Window
    global note_f_button
    path = os.path.join(sys.path[0], "Notes/")
    note_files = [f for f in os.listdir(path)]
    note_f_button = []
    if len(note_files)>0:
        y=60
        for i in range(len(note_files)):
            note_f_button.append(Button(root, bg=frame_color, fg=font_color, activebackground=frame_color, activeforeground=font_color, bd ="0", text=note_files[i], font=("Helvetica Neue Bold", "10"), cursor="hand2", command=lambda: open_note(note_files[i])))
            note_f_button[i].place(x=55, y=y)
            y+=40
    root.update()

def open_note(f_name): #To operate Note Window
    global note_text
    if note_text != None:
        note_text.place_forget()
        note_text = None
    path = os.path.join(sys.path[0], "Notes/")
    with open(f"{path}{f_name}", "r") as file:
        note_text = file.read()
    note_text = Label(root, text=note_text, bg=frame_color, fg=font_color, font=("Helvetica Neue Bold", "11"))
    note_text.place(x=340, y=60)
    root.update()


root = Tk()
root.title("TEST")
root.geometry("706x462")

note_window()


root.update()
root.mainloop()

Here is the output:
enter image description here
You would understand it best if you run it yourself!! If you try this code, be sure to change the font style as Helvetica may not be installed in your system!!

The problem I am facing is that both the files show the same text when clicked, or more specifically, both of them show the same text from the test.txt file.

Can anyone please provide a way to do what I am trying to achieve and also point out where I am doing it wrong.

I am using Python 3.8.3.

sloth
  • 99,095
  • 21
  • 171
  • 219
Sobhan Bose
  • 114
  • 9
  • 1
    See [lambda-in-for-loop-only-takes-last-value](https://stackoverflow.com/questions/33983980/lambda-in-for-loop-only-takes-last-value) – acw1668 Jun 08 '20 at 03:40
  • @acw1668 Thank you for your quick and efficient reply!! Really appreciate it! – Sobhan Bose Jun 08 '20 at 03:46

0 Answers0