In previous post we discussed how to create a simple window using ironpython to display hello world. Now let’s take this a bit ahead and see how to work with labels. Like any other language you can add or edit windows form labels in ironpython. At the end of this article you’ll learn how to modify the label properties for windows form.
Step 1 : Import System and CLR library files and then add references to Drawing and Windows Forms. You should have following code :
import sys import clr clr.AddReference("System.Drawing") clr.AddReference("System.Windows.Forms")
Step 2: With label you can control following four properties :
- Text
- Location
- Width
- Height
Your code will be something like this :
self.label = Label() self.label.Text = "This is Label Demo" self.label.Location = Point(100, 150) self.label.Height = 50 self.label.Width = 250 self.Controls.Add(self.label)
Line 1 will invoke label() function. Line 2 will be used to overwrite the default text with your text. Line 3 is used to set the location using point() function. Line 4 and 5 allows you to modify the height and width respectively. At the end Line 6 Allows you to add label control to your form.
Step 3 : Now that you’re using functions from Drawing and Forms class you need to mention the class relation at the beginning of the code. Your code should look like this :
from System.Drawing import Point from System.Windows.Forms import Application, Form, Label
Step 4: Make sure you pay attention to indentation in your code. One mistake with indentation and ironpython compiler will flag for error.
Step 5: Initialize form and complete the program. Your initialization code should look like this.
form = LabelDemoForm() Application.Run(form)
Step 6: Your complete code should look like this (Note – again as explained in step 5 make sure you pay attention to indentation).
import clr clr.AddReference("System.Drawing") clr.AddReference("System.Windows.Forms") from System.Drawing import Point from System.Windows.Forms import Application, Form, Label class LabelDemoForm(Form): def __init__(self): self.Text = 'Hello World' self.label = Label() self.label.Text = "This is Label Demo" self.label.Location = Point(100, 150) self.label.Height = 50 self.label.Width = 250 self.Controls.Add(self.label) form = LabelDemoForm() Application.Run(form)
You can execute the above code using command line interpreter or from Sharpdevelop or Visual Studio.