1chenar 1chenar - 3 years ago 181
Python Question

Message Box in IronPython with WPF

I'm trying to create a simple GUI using WPF in VS2017. I've tried following code to show a MessageBox after clicking generate button:

import wpf
from System.Windows import MessageBox
def generate_Btn_Click(self, sender, e):
MessageBox.Show("hi")


and it will show up if I click on the generate button but, if I try to add an if statement before
MessageBox.Show()
:

def generate_Btn_Click(self, sender, e):
if A == None:
MessageBox.Show("Message1!")
else:
MessageBox.Show("Message2!")


after clicking on generate button, no MessageBox appears and the window closes. My question is how to use MessageBox In IronPython using WPF.
A simple example that will not work when I push the button is as follows:

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


This is the 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>

Answer Source

When I ran from cmd, here is the error I got:

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

You cannot define global variables inside class!

And now here is a quick fix for you:

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())
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download