IronPython + Wpf 上的按钮单击事件

Button Click Event on IronPython + Wpf

我是 python 和 VS 的新手,我正在尝试制作一个带有按钮的简单 GUI。 单击按钮后,我希望它打印(5)。

代码如下所示,但是当我单击 "run" 时,它没有任何操作就退出了:

import wpf

from System.Windows import Application, Window

class MyWindow(Window):
    def __init__(self):
        wpf.LoadComponent(self, 'WpfApplication1.xaml')

    BUTTON.Click += self.Button_Click
    print(5)

def Button_Click(self, sender, e):
    pass

if __name__ == '__main__':
    Application().Run(MyWindow())

XAML:

<Window 
       xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
       xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
       Title="WpfApplication1" Height="300" Width="300"> 
       <Grid>
        <Button x:Name="BUTTON" Content="Button" HorizontalAlignment="Left" Margin="101,82,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click" Background="#FFFF1616"/>
    </Grid>
</Window> 

谢谢。

您必须为按钮单击添加一个事件处理程序。只需将其添加到您的 window 初始化。 (BUTTON 应与您的 xaml 代码中的按钮名称相匹配)

ui = wpf.LoadComponent(self, 'WpfApplication1.xaml')
ui.BUTTON.Click += self.Button_Click

您也可以通过 xaml 代码实现同样的效果:

 <Button x:Name="BUTTON" Click="Button_Click"></Button>

带有以下注释的工作代码:

import wpf

from System.Windows import Application, Window

class MyWindow(Window):
    def __init__(self):
        self.ui = wpf.LoadComponent(self, 'form.xaml')
        # not needed because event handler
        # is in XAML
        # to handle event on code, remove this from xaml's button tag:
        # Click="Button_Click"
        # and uncomment line below:
        # self.ui.Button.Click += self.Button_Click

    def Button_Click(self, sender, e):
        print('Button has clicked')

if __name__ == '__main__':
    Application().Run(MyWindow())
    # Alternatively, below also works:
    # form = MyWindow()
    # form.ShowDialog()

查看工作表截图: