Here is the original code, where I created a wx.TextCtrl
attributes self.tc1
, the binding event works fine:
import wx
class Example(wx.Frame):
def __init__(self, title):
super().__init__(None, title=title)
self.panel = wx.Panel(self)
self.tc1 = None
self.initUI()
def initUI(self):
sizer = wx.GridBagSizer(2, 2)
self.set_name(sizer)
self.panel.SetSizer(sizer)
sizer.Fit(self)
def set_name(self, sizer):
text1 = wx.StaticText(self.panel, label="Enter your name:")
sizer.Add(text1, pos=(0, 0), flag=wx.LEFT | wx.TOP | wx.BOTTOM, border=10)
self.tc1 = wx.TextCtrl(self.panel, style=wx.TE_CENTER, value="enter_name_here")
self.tc1.Bind(wx.EVT_TEXT, self.on_get_text)
sizer.Add(self.tc1, pos=(0, 1), flag=wx.TOP|wx.RIGHT|wx.BOTTOM|wx.EXPAND, border=5)
def on_get_text(self, e):
print(self.tc1.GetValue())
if __name__ == '__main__':
app = wx.App()
Example("Example").Show()
app.MainLoop()
What if I want to let the text control self.tc1
to be local variable to the method self.set_name
, because I don't want to pollute the class with too many attributes. To be clear, if I change the method self.set_name
this way, making the tc1
a local variable to that method:
def set_name(self, sizer):
text1 = wx.StaticText(self.panel, label="Enter your name:")
sizer.Add(text1, pos=(0, 0), flag=wx.LEFT | wx.TOP | wx.BOTTOM, border=10)
tc1 = wx.TextCtrl(self.panel, style=wx.TE_CENTER, value="enter_name_here")
# tc1.Bind(wx.EVT_TEXT, self.on_get_text)
sizer.Add(tc1, pos=(0, 1), flag=wx.TOP|wx.RIGHT|wx.BOTTOM|wx.EXPAND, border=5)
How can I modify the Bind method to achieve the same effects? I have too many widgets in the class, I really don't want to make every one of them a class attributes.
the EVT_TEXT event that is passed to the handler holds a reference to the object that it's bound to. To get that object call GetEventObject()
def on_get_text(self, event):
tc1 = event.GetEventObject()
print(tc1.GetValue())