PyObjC Tutorial

A small tutorial to start with Python and Cocoa

(c) 2005 Jean Bovet

Introduction

This small tutorial will teach you how to build a small application using Python and the Cocoa framework. It is assumed that Xcode 2.1 and Python are already installed on your system (Python should be installed by default on Mac OS 10.4 and Xcode can be installed using the free developer DVD that come with your Mac box).

Content

  1. Create the project in Xcode 2.1
  2. Create the custom executable
  3. Build and run the default application
  4. Create the interface - part I
  5. Create the interface - part II
  6. Create the interface - part III
  7. Conclusion
  8. Links
  9. Download
  10. Comments

1. Create the project in Xcode 2.1

Just before starting coding, make sure you have Xcode 2.1 (or greater) and PyObjC 1.3.7 (or greater) installed. Click here to download the latest version of Xcode and here to download the latest version of PyObjC.

  • Open Xcode 2.1
  • Select File > New Project
  • Choose PyObjC Application
  • Enter the project name PyObjCTutorial
  • Click the Finish button
  • Make sure to disable 'tabs' indentation in the preferences (under Indentation) because Python uses space instead of tab to ident code.

2. Create the custom executable (if necessary)

If you have a custom executable under the Executables group (like in the image above), you can skip this chapter.

  • Create a custom executable by selecting command Project > New Custom Executable
  • Enter PyObjCTutorial as the name of the executable and /usr/bin/env for the executable path
  • Control-click on the new executable icon and choose Get Info
  • Under the Arguments tab, add the following argument and variable to the environment (see image below)
    • PyObjCTutorial.app/Contents/MacOS/PyObjCTutorial
    • USE_PDB = 1

If you have any problem creating the custom executable, look at this page for more information.

3. Build and run the default application

Select Build > Build and Run (Command-R) to see what happen. A basic Cocoa application will show up: you can see a window, open the print panel, display the about box and so on.

4. Create the interface - part I

Now, let's add some elements in the window to make something more interesting ;-)

We will build a small interface where a button will generated a random number in a text field. Another button will allow us to enable or disable the interface.

  • Quit the application and return to Xcode
  • Open the Resources group and double-click on the MainMenu.nib file
  • Create a window similar to this one:

You will have to create a button, a text field and a check box. You have to drag each object from the Cocoa palet to the window.

To rename the button, simply double-click on it. Make sure you have the check-box selected (check the button Selected in the Attributes inspector - press Command-1 to display the inspector).

First, let make an action in order for our Generate button to invoke a method in our Python object.

  • Select the blue cube PyObjCTutorialAppDelegate in the MainMenu.nib window - the blue cube represents an instance of a class

  • Click on the Classes tab
  • Make sure the Attributes inspector is visible (press Command-1 to select and display it)
  • Add an action named generate as illustrated below

  • Click on the Instances tab (in the MainMenu.nib window)
  • Click and drag while pressing the control key to create a link between the Generate button and the PyObjCTutorialAppDelegate object

  • Double-click on the generate action in the inspector to activate the link

This seems complicated at first, but after a few times, this procedure will be really fast ;-)

Let's go back to Xcode and click on the PyObjCTutorialAppDelegate.py file to display its content in the Xcode editor. We will now create the Python method that will be called by the Generate button.

def generate_(self, sender):
    print sender.title()

This method will print the name of the sender which is the Generate button in our example. Note that the _ (underscore) comes because the equivalent Objective-C method that we would write is the following:

- (IBAction)generate:(id)sender

All : (colon) in Objective-C method call are replaced by _ (underscore) in Python.

Build and run the application (Command-R) and click on the Generate button. You should see the string Generate in the Console.

5. Create the interface - part II

Now, let's generate the random number and put it in the text field. To do that, we have to access the content of the text field from the Python class. We will use the Cocoa bindings (see Links for more info) to do that.

  • Go back to Interface Builder
  • Select the text field in the window

  • Select the Bindings inspector (Command-4)
  • Expand the value binding
  • Choose PyObjCTutorialAppDelegate under the Bind to pop-up

  • Type the name of binding randomValue

  • That's all we have to do in Interface Builder

Go back to Xcode and modify the PyObjCTutorialAppDelegate.py file to be the following:

import random
import objc

class PyObjCTutorialAppDelegate(NibClassBuilder.AutoBaseClass):

    randomValue = objc.ivar(u"randomValue")
    
    def generate_(self, sender):
        self.randomValue = random.random()
Notes
  • We have to import the objc and random modules
  • The objc.ivar() function "links" the randomValue variable and the corresponding bindings in the nib file. Each time you modify this variable, the corresponding bindings is modified (and vice-verse, if you modify the text field value, the Python variable is modified)

Build and run the application (Command-R). Click on the Generate button and check that the random values are automatically updated in the text field thanks to the underlying Cocoa bindings.

6. Create the interface - part III

We will now modify our interface and add the code required to enable or disable the Generate button and the text field when the Enable button is selected or deselected.

  • Go back to Interface Builder
  • Select the PyObjCTutorialAppDelegate blue cube and add an action named enable and link the Enable button with this action
  • In the inspector add two outlets that we will use to link the Generate button and the text field

  • Link these two outlets with their corresponding elements in the window (control-drag from the blue cube to the interface)

  • Make sure you have the two outlets correctly binded

Now, let's go back to Xcode create the enable_() method:

def enable_(self, sender):
    self.generateButton.setEnabled_(sender.state() == NSOnState)
    self.randomField.setEnabled_(sender.state() == NSOnState)

This method will enable the button and text field only if the sender state (the Enable check-box) has the state NSOnState (which stands for the selected state). Use NSOffState to know if the check-box is deselected.

Note that you don't need to declare the generateButton or randomField members: they are automatically declared by PyObjC.

Build and run the application (Command-R). Click on the Enable check-box to see the button and text field being disabled.

Exercises left to the reader:

  • Use the Cocoa binding to enable/disable the Generate button and the text field (that is, remove the outlets that we built in this tutorial and use only the bindings - not code at all needed, all can be done from within Interface Builder)
  • Use a number formatter to format the number in the text field (all can be done from within Interface Builder)

7. Conclusion

Well, that's all for now! More to come over the semester...

8. Links

The Home Page of PyObjC:
http://pyobjc.sourceforge.net/index.php

Complete description of how to create a custom executable and how to deal with Xcode templates:
http://pyobjc.sourceforge.net/doc/xcode-templates.php

Using PyObjC for developing Cocoa applications with Python (Apple):
http://developer.apple.com/cocoa/pyobjc.html

Intro to Cocoa bindings:
http://www.cocoadevcentral.com/articles/000080.php

Cocoa bindings examples and hints:
http://homepage.mac.com/mmalc/CocoaExamples/controllers.html

Apple developer page about Cocoa bindings:
http://developer.apple.com/documentation/Cocoa/Conceptual/CocoaBindings/index.html

9. Download this tutorial (09/27/2005)

Binary and source code for Mac OS X (requires Xcode 2.1):

tutorial.zip (48 KB)

10. Comments and suggestions

Send any comments, suggestions or bug reports to jbovet at cs.usfca.edu