我正在尝试在 VS2017 中使用 WPF 创建一个简单的 GUI。我尝试使用以下代码在单击生成按钮后显示消息框:
import wpf
from System.Windows import MessageBox
def generate_Btn_Click(self, sender, e):
MessageBox.Show("hi")
如果我单击生成按钮,它就会显示,但是,如果我尝试在 MessageBox.Show()
之前添加 if 语句:
def generate_Btn_Click(self, sender, e):
if A == None:
MessageBox.Show("Message1!")
else:
MessageBox.Show("Message2!")
单击“生成”按钮后,不会出现任何消息框,并且窗口会关闭。我的问题是如何使用 WPF 在 IronPython 中使用 MessageBox。 一个简单的例子,当我按下按钮时不起作用:
import wpf
from System.Windows import MessageBox
from System.Windows import Application, Window
class MyWindow(Window):
def __init__(self):
wpf.LoadComponent(self, 'IronPython5.xaml')
str1 = ""
def Button_Click(self, sender, e):
if str1 == "":
MessageBox.Show("msg1")
else:
MessageBox.Show("msg2")
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="IronPython5" Height="300" Width="300">
<Grid>
<Button Content="Button" HorizontalAlignment="Left" Margin="159,238,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>
</Grid>
</Window>
最佳答案
当我从 cmd 运行时,这是我得到的错误:
C:\Program Files (x86)\IronPython 2.7>ipy wpfapp.py
Traceback (most recent call last):
File "wpfapp.py", line 19, in <module>
File "wpfapp.py", line 10, in Button_Click
NameError: global name 'str1' is not defined
你不能在类中定义全局变量!
现在为您提供一个快速解决方案:
import wpf
from System.Windows import MessageBox
from System.Windows import Application, Window
class MyWindow(Window):
def __init__(self):
self.str1 = ""
wpf.LoadComponent(self, 'app.xaml')
def Button_Click(self, sender, e):
if self.str1 == "":
MessageBox.Show("msg1")
else:
MessageBox.Show("msg2")
pass
if __name__ == '__main__':
Application().Run(MyWindow())
关于python - 带 WPF 的 IronPython 中的消息框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45272137/