pythonmacosfiletext-editorfinder

How to receive file when file is opened in python


I am trying to create an app that could open files, like a text editor, in python. But I am running into a problem; I have no way of knowing what file to open. Ex. If I am on my Mac's Finder, and I want to open a file, my app should be an app I could open said file with. My first assumption was that it is passed as an argument when the app is launched. But after looking at the result of sys.argv, I don't see the file. It doesn't matter if I get the file path or the content of the file. I don't know how else to access it. Any help would be appreciated!

This is a base example of my code:

import sys


# This doesn't work!
args = sys.argv
if len(args) > 1:
    file = args[1]
else:
    file = "No file was provided"
# -------------------------------

# Display file

(I am compiling my app using py2app, and using tkinter but am open to alternatives)


Solution

  • For tkinter, the Tk() root has functionality for capturing different events from the OS. The event for opening documents is ::tk::mac::OpenDocument. To create a callback function to handle the event, use createcommand('::tk::mac::OpenDocument', callback).

    Here is a basic example:

    import tkinter
    
    root = tkinter.Tk('Open File')
    
    file_text = tkinter.Text(root)
    file_text.pack()
    
    def callback(*files):
        for f in files:
            # Open File and write it to the screen
            with open(f) as file:
                text = file.read()
                file_text.insert(tkinter.END , text)
    
    root.createcommand('::tk::mac::OpenDocument', callback)
    
    root.mainloop()