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()
        panel.setCanCreateDirectories_(True)
        panel.setCanChooseDirectories_(True)
        panel.setCanChooseFiles_(True)
        #… there are lots of options, you see where this is going…
         if panel.runModal() == NSOKButton:
                    return panel.filename()
        return 

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:

return panel.directory()

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.

Advertisements
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:

WordPress.com Logo

You are commenting using your WordPress.com 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: