Open a file from pc into tkinter

1.1k Views Asked by At

It is possible to open a file in tkinter from pc using right click->Open with->My Program. I just want the file path when using this method.

1

There are 1 best solutions below

1
AudioBubble On

You can't open a file using the method you are asking for( right-click > Open with > My Program) but you can create a program to open and edit files within a GUI using the Tkinter file dialog library and the open() function.

An example of the Method I am talking about:

from tkinter import *
from tkinter.filedialog import askopenfilename

windows = Tk()
windows.title("File Dialog Example")
windows.geometry("500x500")


def file_open():
    text_window.delete('1.0', END)
    filePath = askopenfilename(
        initialdir='C:/', title='Select a File', filetype=(("Text File", ".txt"), ("All Files", "*.*")))
    with open(filePath, 'r+') as askedFile:
        fileContents = askedFile.read()

    text_window.insert(INSERT, fileContents)
    print(filePath)


open_button = Button(windows, text="Open File", command=file_open).grid(row=4, column=3)
text_window = Text(windows, bg="white",width=200, height=150)
text_window.place(x=50, y=50)

windows.mainloop()

And in order to save the changes to the file, you can read the contents in the Text Box and then write the contents to the Opened file.

Thanks