jerrythebum
jerrythebum

Reputation: 362

wxPython using variable to reference an object

I am trying to pass the name of an object into a function so that I can manipulate it from within a function. I have about 14 radio buttons that I want to change depending on what is clicked. Using the function cuts down on code reuse. However the object tries to use the name of the variable as the object name, not the string contained within.

Is it possible to use this string to refer to the object name compared to the string itself?

    self.myObject.GetValue():
    self.writeLine('hello','myObject')

    self.myObject2.GetValue():
    self.writeLine('test','myObject2')

    def writeLine(self,str, objName):
        print str
        self.objName.Enable(False)
        self.objName.SetValue(False)


   self.objName.Enable(False)
AttributeError: 'myProg' object has no attribute 'objName'

Upvotes: 0

Views: 65

Answers (1)

Rolf of Saxony
Rolf of Saxony

Reputation: 22443

Ignoring the obvious errors in the posted code because you wouldn't be able to run it, if your actual code was as stated, you can pass the object rather than a string.
Then in the function use the object passed not self.objName which doesn't exist!

Here's an utterly pointless piece of code to demonstrate:

import wx

class ButtonFrame(wx.Frame):
    def __init__(self, value):
        wx.Frame.__init__(self,None)
        self.btn1 = wx.Button(self, -1, ("Button A"))
        self.btn2 = wx.Button(self, -1, ("Button B"))
        self.btnSizer = wx.BoxSizer(wx.HORIZONTAL)
        self.btnSizer.Add(self.btn1 , 0, wx.RIGHT, 10)
        self.btnSizer.Add(self.btn2 , 0, wx.RIGHT, 10)
        self.btn1.Bind(wx.EVT_BUTTON, self.OnPressA)
        self.btn2.Bind(wx.EVT_BUTTON, self.OnPressB)
        self.SetSizer(self.btnSizer)
        self.Centre()
        self.Show()
        

        self.btn1.Enable(False)
        
        mystr = self.btn1.GetLabel()
        self.writeLine(mystr,self.btn1)
    
        self.writeLine('test',self.btn2)
    
    def writeLine(self,str, objName):
        print(str)
        x = objName.IsEnabled()
        objName.Enable(not x)

    def OnPressA(self,evt):
        self.btn1.SetLabel('Button C')
        self.Layout()

    def OnPressB(self,evt):
        self.btn2.SetLabel('Button D')
        self.Layout()

if __name__ == "__main__":
    app = wx.App(False)
    ButtonFrame(None)
    app.MainLoop()

Initially, as you can see button A is disabled button B is enabled.
The result should be:
Button A is Enabled
Button B is Disabled
Printed on the command line should be Button A followed by test

Upvotes: 1

Related Questions