我是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>
谢谢。
答案 0 :(得分: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()