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.
Asked
Active
Viewed 1,006 times
0
-
Sure, you can use RegEdit to create a "Open With" option. That answer isn't specific to Python or tkinter, though.... What do you mean "get the file path"? – OneCricketeer Dec 02 '21 at 15:01
-
To simplify what I want. I have a GUI with Listbox in it. Let's say I want to open a txt file with my program. All I want to do is to get the txt file path and insert it to my Listbox. I dont want the content of the txt file, only the path. I know about filedialog but I wanted to do with right click txt file->Open with->My Program – Lyk Koss Dec 02 '21 at 19:27
-
Assuming windows, you need to convert your app to an exe, or use `python.exe script.py %1`. See example here https://idojo.co/how-to-add-custom-open-with-command-to-windows-context-menu/ – OneCricketeer Dec 02 '21 at 19:43
1 Answers
0
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