I imagine this is a noob question, though coming from a noob … it’s warranted. I have an app where a menu item exists that I want to use to call an external module (a wx.dialog). I imported the module as such:
from module_name import class_name
Now, I’m stumped on how to start the module when I press the menu item in my wxPython app?
Error:
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
Abridged code … for sake of brevity:
Menu bar from class:
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
The function called:
def OnConvert(self,e):
dlg = Converter()
dlg.ShowModal()
dlg.Destroy()
This is the autonomous module/class:
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()
Bind the menu event to a menu handler and then in the event handler, you instantiate your class. So something like this:
See also http://www.blog.pythonlibrary.org/2008/07/02/wxpython-working-with-menus-toolbars-and-accelerators/ or http://wiki.wxpython.org/WorkingWithMenus
EDIT: As is obvious, the Converter class accepts 3 arguments: self, parent and title. You have to provide those when you instantiate a dialog:
Here are some documentation links on dialogs and how to read tracebacks: