我正在教授使用 Python 进行编程和 GUI 开发的入门类(class),我发现对于刚接触编程的学生来说,最简单的解决方案是使用 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())
我注意到,每当我尝试手动修改 XAML 以命名元素时,GUI 元素都没有名称并且 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:
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="IronPyWpf" Height="300" Width="300">
<Grid>
<Button x:Name="button" Content="Button" Height="23" HorizontalAlignment="Left" Margin="103,226,0,0" VerticalAlignment="Top" Width="75" />
<TextBox x:Name="textbox" Height="182" HorizontalAlignment="Left" Margin="24,21,0,0" VerticalAlignment="Top" Width="237" />
</Grid>
</Window>
然后您可以定义两个名为按钮和文本框的属性来访问 UI 元素:
class MyWindow(Window):
def __init__(self):
wpf.LoadComponent(self, 'IronPyWpf.xaml')
self._button.Content = 'My Button'
self._textbox.Text = 'My Text'
def get_button(self):
return self._button
def set_button(self, value):
self._button = value
button = property(get_button, set_button)
def get_textbox(self):
return self._textbox
def set_textbox(self, value):
self._textbox = value
textbox = property(get_textbox, set_textbox)
事实上,您似乎可以通过删除属性定义来进一步简化代码:
class MyWindow(Window):
def __init__(self):
wpf.LoadComponent(self, 'IronPyWpf.xaml')
self.button.Content = 'My Button'
self.textbox.Text = 'My Text'
不幸的是,正如您已经看到的那样,当您尝试编辑 XAML 并为 UI 元素命名时,Visual Studio 似乎崩溃并出现空引用异常。
关于python - 使用 IronPython 和 Visual Studio 2010 进行 GUI 开发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5853812/