我正在教一门使用Python进行编程和GUI开发的入门课程,我发现对于刚接触编程的学生来说,最不容易的解决方案是使用Visual Studio进行GUI开发。
虽然使用C#和VB的GUI开发经验令人愉快,但我找不到使用IronPython的方法。我安装了包含Visual Studio工具的IronPython 2.7.1,并创建了一个WPF IronPython项目。
我可以像VB和C#一样使用WPF表单设计器,但是,我找不到一种方便的方式(即学生可以理解)来访问GUI元素。例如,使用VB,可以根据元素的名称引用元素,然后可以修改其中的属性。使用IronPython(我不打算向学生展示)我能做的最好的事情是:
import wpf
from System.Windows import Application, Window
class MyWindow(Window):
def __init__(self):
wpf.LoadComponent(self, 'WpfApplication3.xaml')
def Button_Click(self, sender, e):
#This is the only way I could find in which I can
#access an element and modify its properties
self.Content.Children[1].Text += 'Hello World\n'
if __name__ == '__main__':
Application().Run(MyWindow())
我注意到GUI元素没有名字,每当我试图手动修改XAML来命名元素时,Visual Studio就会崩溃。下面是为带有按钮和文本区域的简单框架生成的XAML:
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="WpfApplication3" Height="300" Width="300">
<Grid>
<Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="103,226,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click" />
<TextBox Height="182" HorizontalAlignment="Left" Margin="24,21,0,0" VerticalAlignment="Top" Width="237" />
</Grid>
</Window>
如果有任何帮助,使这对学生更容易将不胜感激。对于Python GUI开发,我也愿意接受其他建议,这些建议提供了类似于Visual Studio的体验。
在IronPython 2.7中,wpf.LoadComponent方法将连接与XAML UI元素同名的任何属性。如果您使用的是IronPython 2.6,那么您需要使用WombatPM建议的代码。因此,对于IronPython 2.7,如果使用以下XAML:
然后,可以定义两个名为button和textbox的属性来访问UI元素:
实际上,通过删除属性定义,您似乎可以进一步简化代码:
不幸的是,正如您已经看到的,当您试图编辑XAML并为UI元素命名时,Visual Studio似乎会崩溃,出现空引用异常。
您需要遍历所有对象,并使用类似的函数创建更容易理解的引用。
请参阅http://www.ironpython.info/index.php/XAML_GUI_Events_Example获取上述代码和完整示例。
相关问题 更多 >
编程相关推荐