如何在类中放置消息对话框过程并调用它

时间:2014-02-20 23:10:39

标签: wxpython

假设我想在一个带有字符串参数的类中添加一个过程并在消息框中显示它(以及其他一些东西)?我试过这个: 代码:

import wx
import sqlite3

# Create a new frame class, derived from the wxPython Frame.
class MyFrame(wx.Frame):

    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title)

        panel = wx.Panel(self, -1)
        self.panel = panel

# Every wxWidgets application must have a class derived from wx.App
class MyApp(wx.App):
    def OnInit(self):

        frame = MyFrame(None, -1, "This is a test")
        frame.Show(True)

        self.SetTopWindow(frame)
        return True

    def inform(self, s):
        wx.MessageBox(s + 'XXX', 'Info', wx.OK | wx.ICON_INFORMATION)



app = MyApp(0)    
app.inform("hello")
app.MainLoop()   

错误讯息: C:\ chris \ python \ wxwidgets> python SO20140220.py Traceback(最近一次调用最后一次):   文件“SO20140220.py”,第29行,in     app.inform( “你好”) AttributeError:'MyApp'对象没有属性'inform'

1 个答案:

答案 0 :(得分:2)

您的代码适用于Windows 7,wxPython 2.9和Python 2.7。但是,我不认为你应该在app对象本身上调用方法。您应该在 OnInit 中调用通知,如下所示:

import wx
import sqlite3

# Create a new frame class, derived from the wxPython Frame.
class MyFrame(wx.Frame):

    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title)

        panel = wx.Panel(self, -1)
        self.panel = panel

# Every wxWidgets application must have a class derived from wx.App
class MyApp(wx.App):
    def OnInit(self):

        frame = MyFrame(None, -1, "This is a test")
        frame.Show(True)

        self.SetTopWindow(frame)
        self.inform("hello")
        return True

    def inform(self, s):
        wx.MessageBox(s + 'XXX', 'Info', wx.OK | wx.ICON_INFORMATION)



app = MyApp(0)
app.MainLoop()   

或者您可以删除wx.App的整个子类并使代码更短,如下所示:

import wx
import sqlite3

# Create a new frame class, derived from the wxPython Frame.
class MyFrame(wx.Frame):

    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title)

        panel = wx.Panel(self, -1)
        self.panel = panel
        self.Show()
        self.inform("hello")

    def inform(self, s):
        wx.MessageBox(s + 'XXX', 'Info', wx.OK | wx.ICON_INFORMATION)

app = wx.App(0)
frame = MyFrame(None, -1, "This is a test")
app.MainLoop()