Sai Varun Prasanth
Sai Varun Prasanth

Reputation: 1

How to create textCtrl box dynamically?

Is there a way to create textCtrl box dynamically by clicking a button? So I am planning to build a GUI where I provide one TextCtrl box for the user to enter one value by default.But if the user wants one more value to enter ,there should be a '+' or Add button where the user can create so that the program can dynamically create one more textCtrl box and display it in the GUI ,so that the User can enter their input in that newly created TextCtrl box!

Thanks in Advance!

Upvotes: 0

Views: 673

Answers (1)

Mike Driscoll
Mike Driscoll

Reputation: 33111

That's actually pretty easy. Here's one way to do it:

import wx

########################################################################
class MyPanel(wx.Panel):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        wx.Panel.__init__(self, parent)

        self.mainSizer = wx.BoxSizer(wx.VERTICAL)
        self.txtSizer = wx.BoxSizer(wx.VERTICAL)

        txt = wx.TextCtrl(self)
        self.txtSizer.Add(txt, 0, wx.EXPAND|wx.ALL, 5)
        self.mainSizer.Add(self.txtSizer, 0, wx.EXPAND, 5)

        add_btn = wx.Button(self, label="Add")
        add_btn.Bind(wx.EVT_BUTTON, self.onAdd)
        process_btn = wx.Button(self, label="Process")
        process_btn.Bind(wx.EVT_BUTTON, self.onProcess)

        self.mainSizer.Add(add_btn, 0, wx.ALL, 5)
        self.mainSizer.Add(process_btn, 0, wx.ALL, 5)

        self.SetSizer(self.mainSizer)

    #----------------------------------------------------------------------
    def onAdd(self, event):
        """"""
        self.txtSizer.Add(wx.TextCtrl(self), 0, wx.EXPAND|wx.ALL, 5)
        self.mainSizer.Layout()

    #----------------------------------------------------------------------
    def onProcess(self, event):
        """"""
        children = self.txtSizer.GetChildren()
        for child in children:
            widget = child.GetWindow()
            if isinstance(widget, wx.TextCtrl):
                print widget.GetValue()


########################################################################
class MyFrame(wx.Frame):
    """"""

    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        wx.Frame.__init__(self, None, title="Dynamic")
        panel = MyPanel(self)
        self.Show()


#----------------------------------------------------------------------
if __name__ == "__main__":
    app = wx.App(False)
    frame = MyFrame()
    app.MainLoop()

As a bonus, I also show how to get the information out of the text controls too. Note that the tab order gets screwed up when you add a text control.

Upvotes: 1

Related Questions