Skip to main content
 首页 » 编程设计

python之带有 WPF 的 IronPython 中的消息框

2024年10月01日7傻小

我正在尝试在 VS2017 中使用 WPF 创建一个简单的 GUI。单击生成按钮后,我尝试使用以下代码显示 MessageBox:

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())