Search code examples
wxpythontextctrl

How to retrieve text from wx python CtrlText?


I'm trying to retrieve a text value from a TextCtrl object in Python, and I can't seem to get it. The text is named "text" in the code below, I tried to retrieve the value in "Click" function. I understood well how to show the text box and button and how to retrieve the event, but when I run this code, I have an error that says that "myForm" has no attribute "text", How to set "text" as an attribute to myForm? How to get the value from the text object?

from datetime import datetime, time
from pygame import mixer # Load the required library
import wx


class myForm(wx.Frame):


    def __init__(self, parent, title):
        super(myForm, self).__init__(parent,title=title, size=(300, 100))

        hbox = wx.BoxSizer(wx.HORIZONTAL)
        fgs = wx.FlexGridSizer(3, 2, 9, 25)
        panel = wx.Panel(self)
        title = wx.StaticText(panel, label="Time in second")

        button1 = wx.Button(panel, label="Start")
        text=wx.TextCtrl(panel)

        self.Bind(wx.EVT_BUTTON, self.Click)
        fgs.AddMany([(title), (text, 1, wx.EXPAND),(button1,1,wx.EXPAND)])

        fgs.AddGrowableRow(2, 1)
        fgs.AddGrowableCol(1, 1)

        hbox.Add(fgs, proportion=1, flag=wx.ALL|wx.EXPAND, border=15)
        panel.SetSizer(hbox)

        self.Centre()
        self.Show()  


    def Click(self, event):
        print 'event reached frame class'
        #print tc1.GetValue()
        print "value",self.text.GetValue()
        event.Skip()

Solution

  • You need to make the text control into an attribute of your frame's class. So instead of creating it like this:

    text = wx.TextCtrl(panel)
    

    You need to do this:

    self.text = wx.TextCtrl(panel)
    

    Note that text is not the same as self.text.

    Now your event handler will work.