我想这是一个菜鸟问题,虽然来自一个菜鸟......这是有道理的。我有一个应用程序,其中存在一个菜单项,我想用它来调用外部模块(wx.dialog)。我这样导入了模块:
from module_name import class_name
现在,当我按下wxPython应用程序中的菜单项时,我对如何启动模块感到难过?
错误:
Traceback (most recent call last):
File "C:\SQA_log\wxGui_comPort.py", line 141, in OnConvert
dlg = Converter(*args)
NameError: global name 'args' is not defined
简化代码......为简洁起见: 课程栏:
self.SetMenuBar(menuBar)
self.Bind(wx.EVT_MENU, self.OnAbout, id=1)
self.Bind(wx.EVT_MENU, self.OnQuit, id=2)
self.Bind(wx.EVT_MENU, self.OnDisp, id=3)
self.Bind(wx.EVT_MENU, self.OnServ, id=4)
self.Bind(wx.EVT_MENU, self.OnDateTime, id=5)
self.Bind(wx.EVT_MENU, self.OnOpen, id=6)
self.Bind(wx.EVT_MENU, self.OnConvert, id=7)# Here is the menu item I'm using
该函数名为:
def OnConvert(self,e):
dlg = Converter()
dlg.ShowModal()
dlg.Destroy()
这是自治模块/类:
import wx
class Converter(wx.Dialog):
def __init__(self, parent, title):
wx.Dialog.__init__(self, parent, title=title, size=(350, 310))
wx.StaticText(self, -1, 'Convert Decimal to Hex', (20,20))
wx.StaticText(self, -1, 'Decimal: ', (20, 80))
wx.StaticText(self, -1, 'Hex: ', (20, 150))
self.dec_hex = wx.StaticText(self, -1, '', (150, 150))
self.sc = wx.SpinCtrl(self, -1, '', (150, 75), (60, -1))
self.sc.SetRange(-459, 1000)
self.sc.SetValue(0)
compute_btn = wx.Button(self, 1, 'Compute', (70, 250))
compute_btn.SetFocus()
clear_btn = wx.Button(self, 2, 'Close', (185, 250))
wx.EVT_BUTTON(self, 1, self.OnCompute)
wx.EVT_BUTTON(self, 2, self.OnQuit)
wx.EVT_CLOSE(self, self.OnClose)
self.Centre()
self.ShowModal()
self.Destroy()
def OnCompute(self, event):
dec = self.sc.GetValue()
hex1 = "%x" % dec
self.dec_hex.SetLabel(str(hex1).upper())
def OnClose(self, event):
self.Destroy()
def OnQuit(self, event):
self.Close(True)
if __name__ == '__main__':
app = wx.App(False)
dlog = Converter(None, 'Converter')
app.MainLoop()
答案 0 :(得分:2)
将菜单事件绑定到菜单处理程序,然后在事件处理程序中实例化您的类。所以像这样:
def myEventHandler(self, event):
dlg = class_name(*args)
dlg.ShowModal()
dlg.Destroy()
另请参阅http://www.blog.pythonlibrary.org/2008/07/02/wxpython-working-with-menus-toolbars-and-accelerators/或http://wiki.wxpython.org/WorkingWithMenus
编辑:很明显,Converter类接受3个参数:self,parent和title。您必须在实例化对话框时提供这些:
dlg = Converter(None, "MyTitle")
以下是对话框的一些文档链接以及如何阅读回溯: