IronPython Hello World Tutorial


As some of you may have heard IronPython 1.0 has been released. If you don’t’ know what IronPython is, it’s:

a new implementation of the Python programming language running on .NET. It supports an interactive console with fully dynamic compilation. It is well integrated with the rest of the .NET Framework and makes all .NET libraries easily available to Python programmers, while maintaining full compatibility with the Python language.

The cool thing about IronPthon is that it also works with the Windows Presentation Foundation which will be released when Windows Vista is released and available for Windows XP and Windows Vista.

I thought that this was pretty interesting so I thought I’d try playing with it and write a quick tutorial.

Requirement

For this tutorial you need the following:

For this tutorial I has assumed that you have installed IronPython to:

C:\IronPython

The GUI

Once you have everything installed load up Microsoft Expression Interactive Designer (MEID from now on) or sparkle as it used to be called and close the Welcome Screen. You might notice that MEID is very slow, on my system the program just seems to c-r-a-w-l, but it does allow you to do some pretty neat things.

After it has finished loading and clearing the Welcome screen you should be left with a blank canvas. The canvas is too large for the Hello World program we’re creating so resize the canvas until it has reached a suitable size.

Then with the canvas selected, select the Background item in the Appearance pallet and set the background of the canvas (our window) to something suitable using the colour picker below. I selected a nice dark shade of green.

Sparkle

The next step is to add a button to our window. To do this select the Button item in the Library palette and draw the button onto the canvas.

Sparkle Button

Sparkle Button

Next we want to do change the text on the button to be “Press me!” to do that select the Text tool in the Tools pallet (it is the solid black letter A) and click on the button. You can now edit the text, so delete the “button” text and type “Press me!” Select the selection tool in the Tools pallet (the black arrow) when you are done.

The next thing to do is save your project (to whatever folder you wish) and then export your xaml code (File | Export XAML) to:

C:\IronPython\Projects\HelloWorld\hw.xaml

The Code

The reference for almost all of this code is the tutorial and sample applications that can be found on the IronPython website. If you want to go further then this tutorial, or if you want to understand every line of code I suggest you start there.

The first thing to do is create our HelloWorld.py file in:

C:\IronPython\Projects\HelloWorld\

Now we have to import a whole bunch of stuff and create some helper functions. This code was taken from the IronPython tutorial file avalon.py, which should be installed in your C:\IronPython\Tutorial directory It had to change it slightly since it crated a System.Windows.Application object which has to be a singleton.

import clr

clr.AddReferenceByPartialName("PresentationCore")
clr.AddReferenceByPartialName("PresentationFramework")
clr.AddReferenceByPartialName("WindowsBase")
clr.AddReferenceByPartialName("IronPython")

from math import *
from System import *
from System.Windows import *
from System.Windows.Media import *
from System.Windows.Media.Animation import *
from System.Windows.Controls import *
from System.Windows.Shapes import *
from System.Threading import *
from System.Windows.Threading import *

import IronPython

# Taken from the IronPython Samples
def LoadXaml(filename):
    from System.IO import *
    from System.Windows.Markup import XamlReader
    f = FileStream(filename, FileMode.Open)
    try:
	element = XamlReader.Load(f)
    finally:
	f.Close()
    return element

# Taken from the IronPython Samples
def Walk(tree):
    yield tree
    if hasattr(tree, 'Children'):
        for child in tree.Children:
            for x in Walk(child):
                yield x
    elif hasattr(tree, 'Child'):
        for x in Walk(tree.Child):
            yield x
    elif hasattr(tree, 'Content'):
        for x in Walk(tree.Content):
            yield x

This code simply initializes IronPython, the Windows Presentation FrameWork, and creates two helper functions that will make the rest of our code easier.

The next thing that we do is create our main class which is of the type System.Windows.Application and initialize it:

class HelloWorld(Application):

	def __init__(self):
		
		Application.__init__(self)

		# Create the Window System.Windows.Window
		self.window = Window()
		# Load the Xaml
		self.window.Content = LoadXaml("hw.xaml")
		# Set the Window Title
		self.window.Title = "Hello World"
		# Make the Window the same size as the Xaml
		self.window.SizeToContent = SizeToContent.WidthAndHeight
		# Connect the buttons with their events
		self.connect_buttons()
		# Show the Window
		self.window.Show()

The first thing that we do is create our application’s window which is of type System.Windows.Window. Then we set the window’s Content to be our xaml code that we load.

Then we set the window’s SizeToContent property to size to the height and width of the content, which is the XAML that we loaded.

Then we call a helper function (not shown yet) which will connect our button’s Click event with a function, and then we call the Show() function to show the window.

The connect_buttons function is defined as follows:

def connect_buttons(self):
	"""Connect the button to its clicked handler"""
	
	for item in Walk(self.window):
		if isinstance(item, Button):
			# It's our one and only button!
			# Connect the click event
			item.Click += self.on_button_clicked

What this function does is walk through all of our window’s children, and if it encounters a button it adds our on_button_clicked() function to that buttons Click handler.

on_button_clicked() is a pretty simple function that sets whatever button was clicked’s text to be “Hello World!”

def on_button_clicked(self, button, *args):
	# Set the Text to be Hello World!
	button.Content = "Hello World"

That’s basically it for the code, all we have to do now is make sure that something happens if this python file is launched directly:

if __name__ == "__main__":
	
	hw = HelloWorld()
	hw.Run()

Then if you want to launch this project and test it out you can start the Windows command line and browse to C:\ItronPython\Projects\HelloWord and launch the following command:

C:\IronPython\Projects\HelloWorld>C:\IronPython\ipy.exe HelloWorld.py

When you do you should be greeted with this:

Windows Presentation WIndow

Here is all the code in one nice window:

import clr

clr.AddReferenceByPartialName("PresentationCore")
clr.AddReferenceByPartialName("PresentationFramework")
clr.AddReferenceByPartialName("WindowsBase")
clr.AddReferenceByPartialName("IronPython")

from math import *
from System import *
from System.Windows import *
from System.Windows.Media import *
from System.Windows.Media.Animation import *
from System.Windows.Controls import *
from System.Windows.Shapes import *
from System.Threading import *
from System.Windows.Threading import *

import IronPython

# Taken from the IronPython Samples
def LoadXaml(filename):
    from System.IO import *
    from System.Windows.Markup import XamlReader
    f = FileStream(filename, FileMode.Open)
    try:
	element = XamlReader.Load(f)
    finally:
	f.Close()
    return element

# Taken from the IronPython Samples
def Walk(tree):
    yield tree
    if hasattr(tree, 'Children'):
        for child in tree.Children:
            for x in Walk(child):
                yield x
    elif hasattr(tree, 'Child'):
        for x in Walk(tree.Child):
            yield x
    elif hasattr(tree, 'Content'):
        for x in Walk(tree.Content):
            yield x

class HelloWorld(Application):

	def __init__(self):
		
		Application.__init__(self)
		# Create the Window System.Windows.Window
		self.window = Window()
		# Load the Xaml
		self.window.Content = LoadXaml("hw.xaml")
		# Set the Window Title
		self.window.Title = "Hello World"
		# Make the Window the same size as the Xaml
		self.window.SizeToContent = SizeToContent.WidthAndHeight
		# Connect the buttons with their events
		self.connect_buttons()
		# Show the Window
		self.window.Show()
		
	def connect_buttons(self):
		"""Connect the button to its clicked handler"""
		
		for item in Walk(self.window):
			if isinstance(item, Button):
				# It's our one and only button!
				# Connect the click event
				item.Click += self.on_button_clicked
	
	def on_button_clicked(self, button, *args):
		# Set the Text to be Hello World!
		button.Content = "Hello World"
		

if __name__ == "__main__":
	
	hw = HelloWorld()
	hw.Run()
selsine

del.icio.us del.icio.us

11 Responses to “IronPython Hello World Tutorial”

  1. Holy wha?
    Says:

    [...] But… -> IronPython Hello World Tutorial [...]

  2. Ian Ozsvald
    Says:

    Here’s a quick hat-tip for you, I mention your blog (this entry gets shown) in my recent 2-part video set that introduces new Python programmers to useful on-line resources:
    http://showmedo.com/videos/video?name=pythonOzsvaldIntroToPyResources2&fromSeriesID=27

    I’m looking forward to seeing more tutorials on here :-)
    Ian.

  3. selsine

    selsine
    Says:

    Hey Ian,

    That is too cool! Thank you very much for the tip of the hat! Keep up the good work on your site too!

  4. Utopia Parkway » Blog Archive » links for 2006-12-29
    Says:

    [...] learning python Âť Blog Archive Âť IronPython Hello World Tutorial (tags: python) [...]

  5. Rakshith
    Says:

    Finding difficult in executing Iron Python codes using IronPythonConsole.exe

  6. selsine

    selsine
    Says:

    Hi Rakshith,

    What sort of problems are you having? If you explain what you are trying to do and the issues that you are encountering in more detail I may be able to help you with your problem.

  7. Python Mini-Learning Guide « Conocimiento Libre
    Says:

    [...] IronPython Hello World Tutorial (LearningPython.com) [...]

  8. windows vista tutorial
    Says:

    windows vista tutorial

    Nice points…

  9. Ade Murti
    Says:

    Cool..but can u help me how to make python code can be run on the linux that don’t have python compiler? can it be distributed by deb package please help me, and send the tutorial about iron python if its exist??

    Best Regards

    Ade Murti S. MS

  10. selsine

    selsine
    Says:

    Hi Ade,

    Any modern Linux computer should have Python installed so don’t think that you need to worry about that. Generally it’s best to distribute using one of the many package formats that will ensure that the version of Python that you need will be installed.

    I hope this helps.

  11. Yah ok
    Says:

    ImportError: No module named clr

    I may be a not so experienced programmer but this tutorial sure did suck for me. I know it’s near three years old as well but even then I’m sure it wouldn’t have yielded any kind of a result for a non-experienced programmer.

    Hopefully a modernised rewrite one day.

Leave a Reply

 

Popular Posts