Home > Software engineering >  How to open folder in our gui file like vs code in python tkinter?
How to open folder in our gui file like vs code in python tkinter?

Time:03-10

I am creating a function to get all file in my gui like vs code. I tried many times I have created a function through which I am able to get file of folder in my gui but I am unable to open file from my gui and I am also unable to put image before their names according to what extensions is contain

error:-

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 1921, in __call__
    return self.func(*args)
  File "d:\coding notes\pytho project\project1.py", line 24, in <lambda>
    list_box.bind("<<ListboxSelect>>",lambda event=None:Open(file))
  File "d:\coding notes\pytho project\project1.py", line 6, in Open
    with open(value,"r") as f:
PermissionError: [Errno 13] Permission denied: 'D:/coding notes/pytho project'

this is my code

import os
from tkinter import*
from tkinter.filedialog import askdirectory
def Open(value):
    editor.delete(1.0,END)
    with open(value,"r") as f:
        editor.insert(1.0,f.read())
def Open_folder():
    global file 
    file = askdirectory()
    if file == "":
        file = None
    else:
        for i in os.listdir(file):
            list_box.insert(END,i)
root = Tk()
file = ""
root.geometry("1550x850 0 0")
editor = Text(root,font="Consolas 15",bg="gray19",fg="white",insertbackground="white")
editor.place(x=400,y=0,relwidth=True,height=850)
Button(root,text="Open folder",font="Consolas 10",relief=GROOVE,bg="gray19",fg="white",command=Open_folder).place(x=0,y=0)
list_box = Listbox(root,font="Consolas 15",bg="gray19",fg="white",selectbackground="gray29")
list_box.place(x=0,y=20,width=400,height=850)
list_box.bind("<<ListboxSelect>>",lambda event=None:Open(file))
root.mainloop()

CodePudding user response:

You open the selected folder instead of the selected file in the listbox inside Open(). You need to get the selected file from the listbox and join the selected folder to get the full filepath:

def Open(value):
    # get the selected filename from listbox
    file = list_box.get(list_box.curselection())
    # get the absolute path of the selected filename
    filepath = os.path.join(value, file)
    
    editor.delete(1.0, END)
    with open(filepath, "r") as f:
        editor.insert(1.0, f.read())
  • Related