Writing A Python Controller

First let's add your new controller into the GUI. Add an object from "Objects & Controllers" into your GUI. Now click on it and bring up the "Identity" tab in the inspector. The first drop-down lets you select a class, find "controller" and pick it.

Now Open up your newly created controller.py with your favorite text editor, and we'll begin.

#  controller.py
#  QuickTag
#  Created by Scott Paul Robertson on 6/11/08.
#  Copyright (c) 2008 __MyCompanyName__. All rights reserved.

from objc import YES, NO, IBAction, IBOutlet
from Foundation import *
from AppKit import *

class controller(NSWindowController):

There are two parts we will be adding, the Outlets (variables) and Actions (methods). first lets add a few outlets to the class controller.

    name = IBOutlet()
    artist = IBOutlet()
    albumArtist = IBOutlet()
    album = IBOutlet()

These class variables can now be connected to various fields in your GUI. In Interface Builder you simply control-click your controller object and drag to the text field that you want to attach that variable to. Wire up the fields as you would expect.

Next we start by adding some actions to the controller. First we add the method awakeFromNib which is called at window creation, allowing us to act at application start time.

    def awakeFromNib(self):
        print "awake"

Now let's write a method that we will wire the "Save & Close" button to.

    def save_(self, sender):
        print "Save"

    def saveClose_(self, sender):
        print "Saving and Closing"

Connect these to buttons or menu entries by control-clicking the button and dragging to the controller. Now if we run the application the console will print messages every time we hit a connected button.

We'll go ahead and write similar functions for our other actions and wire them up. controller.py is the final result of this process.

In the next part we'll look into doing something useful with our controller.

<< Part 2: Starting A Cocoa-Python Application | Part 4: Creating an Open Dialog >>

Posted: Jun 23, 2008 | Tags: python osx programming pyobjc cocoa

Comments are closed.


42 | django | python | oggify | OSCON | OSCON07 | osx | utosc | mythtv | security | reading | music | gaming | programming | tips | shell | vim | pyobjc | cocoa | iphone | blog | git


<< Jun >>
Mo Tu We Th Fr Sa Su
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 1 2 3 4 5 6


This space reserved for a search box

A Django site. Hosted on a Slicehost Slice