按钮单击IronPython + Wpf上的事件

问题描述 投票:1回答:1

我是python和VS的新手,我试图用一个按钮创建一个简单的GUI。一旦我点击按钮,我想要它打印(5)。

代码看起来如下,但当我点击“运行”时它退出而没有任何动作:

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> 

谢谢。

python wpf visual-studio ironpython
1个回答
2
投票

您必须为按钮单击添加事件处理程序。只需将此添加到您的窗口init。 (按钮应与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()

查看工作表格的截图:enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.