2

I have created a program that can edit the contents of a text file. Assume that my program looks something like this:

from tkinter import *
from tkinter import filedialog

root = Tk()


def open_file():
    file_to_open = filedialog.askopenfilename(initialdir="C:/" , filetypes=(("All files" , "*.*"),))
    if file_to_open != "":
        file = open(file_to_open , 'r')
        content_in_file = file.read()
        file.close()
        text.delete('1.0' , END)
        text.insert('1.0' , content_in_file)


def save_file():
    path = filedialog.asksaveasfilename(initialdir="C:/" , filetypes=(("All files" , ""),))
    if path != "":
        file = open(path , 'w')
        file.write(text.get('1.0' , 'end-1c'))
        file.close()


text = Text(root , width = 65 , height = 20 , font = "consolas 14")
text.pack()

open_button = Button(root , text = "Open" , command = open_file)
open_button.pack()

save_button = Button(root , text = "Save" , command = save_file)
save_button.pack(pady=20)

mainloop()

The problem here is that when I click on a text file in my file explorer, it opens with the default windows notepad instead of opening with my program.

What I want is that all the text files should open with my program instead of opening with the default windows Notepad.

Here's what I did (in order):

enter image description here

enter image description here

enter image description here

enter image description here

After completing the following steps, I tried opening my text file, but it says:

enter image description here

I tried converting my python program into an exe file (using pyinstaller) and then following the steps above, but when I open the text file I get an other error:

enter image description here

Is there anything wrong with my code or the steps I followed?

I would really appreciate it if anyone could guide me through how I can open a text file with my program.

2
  • You know that when you open a file with your program Windows passes in the program as an argument. You never handle the argument. Also you can't set your python script as the default application because it isn't a executable. Can you please expand on how you tried to compile it as a .exe and the error? Commented Mar 25, 2021 at 10:31
  • " Can you please expand on how you tried to compile it as a .exe and the error?" @TheLizzard: My bad, I had framed the sentence wrong. There was no error in converting the script into an exe file, but the error occurred when I followed the steps above for the exe file and then opened the text file. I have found the solution anyway, but I have edited my question so that people reading it in the future won't get confused. Commented Sep 16, 2021 at 7:22

1 Answer 1

1

The code looks fine, it just needed to take the argument, when you open-with you are calling some executable on a path o multiple paths, the first argument is de executable itself, so if the code is executed with more than 1 argument it's a path; the problem with this is that the command is python and not file.py, a fix would be convert it to a exe or call it with a bat.

This example may look different but is more or less the same, just packed inside a class.

from tkinter import filedialog
import tkinter as tk
import sys
import os

SRC_PATH = os.path.dirname(__file__)

class File_Editor(tk.Tk):

    def __init__(self):
        tk.Tk.__init__(self)
        self.text = tk.Text(self, width=65, height=20, font="consolas 14")
        self.text.pack()
        self.open_button = tk.Button(self, text="Open", command=self.open_file)
        self.open_button.pack()
        self.save_button = tk.Button(self, text="Save", command=self.save_file)
        self.save_button.pack(pady=20)

    def open_file(self, file=None):
        path = file or filedialog.askopenfilename(
            initialdir=SRC_PATH, filetypes=(("All files", "*.*"),))
        if os.path.exists(path) and os.path.isfile(path):
            with open(path, 'r', encoding='utf-8') as file:
                content_in_file = file.read()
            self.text.delete('1.0', tk.END)
            self.text.insert('1.0', content_in_file)

    def save_file(self):
        path = filedialog.asksaveasfilename(initialdir=SRC_PATH, filetypes=(("All files", ""),))
        if os.path.exists(path) and os.path.isfile(path):
            with open(path, 'r', encoding='utf-8') as file:
                file.write(self.text.get('1.0', 'end-1c'))


if __name__ == '__main__':
    app = File_Editor()
    if len(sys.argv) > 1:
        app.open_file(sys.argv[1])
    app.mainloop()

This .bat file is just passing the firs argument to the file; a full path is required to execute, it will not be called in a directory you expect.

@echo off
python D:\Escritorio\tmp_py\temp_3.py %1

Now you just call the open-with File_Editor.bat

Sign up to request clarification or add additional context in comments.

4 Comments

Why did you set the initial dir to SRC_PATH - just curios
I almost always add it to file management scripts, specialty when its a command line utility for stuff like having a default value for arguments or in testing a module giving it a different execution parameters (in combination with the execution guard), but over all its just preference
@Alex: I haven't actually worked with batch scripts, so can you please explain what do those two lines in the batch file do?
@echo off means don't show the messages in the console, the second line is just a command, like in a terminal, but in a batch you have %* values, those mean arguments, sys.argv[1] is the same as %1; if you pyinstall the .py the .bat file is no longer needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.