Simple OpenFile Dialog in PyObjc

Surprisingly it took me quite a while to figure out how to to this, once again turned out to be pretty simple.
Here we go, first thing make sure Cocoa is imported

from Cocoa import * 

second, define a method like this:

def openFile():
        panel = NSOpenPanel.openPanel()
        #… there are lots of options, you see where this is going…
         if panel.runModal() == NSOKButton:
                    return panel.filename()

now you can call the dialog and store it’s return value like this:

file = openFile()

if you want to choose a directory instead of a file just use:


instead of 

return panel.filename()

you can also return multiple files or filter for specific extension, I’m sure you’ll figure this out yourself.

1 comment
  1. derived said:

    Quick and helpful, thanks. The only problem could be the weird indentation in your example but I’ll live =)

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: