1

Why does the following code create 2 widgets, and not overwrite each other? How would someone reference the first instance vs second instance?

import wx

app = wx.App(False)
frame = wx.Frame(None, -1, "Test", (250,250), (250,250))
panel = wx.Panel(frame, -1)

textbox = wx.TextCtrl(panel, -1, "", (10,10), (135,20))
textbox = wx.TextCtrl(panel, -1, "", (10,40), (135,20))

frame.Show()
app.MainLoop()
1
  • 1
    wxPython has another mechanism in place to hold reference to the object. Basically by having both have panel as parent, the first object is not deleted, but not accessible by textbox name anymore. You have to call Destroy() method on the object first. Commented Dec 24, 2013 at 21:01

2 Answers 2

2

The widgets are created, then assigned to the name. The first one still exists, but it is difficult for you to access it as you have assigned a different object to the name. If you want to still access both of them, try:

textboxes = []
textboxes.append(wx.TextCtrl(panel, -1, "", (10,10), (135,20)))
textboxes.append(wx.TextCtrl(panel, -1, "", (10,40), (135,20)))

Now you can access each by index:

textboxes[0]

Or loop through all of them:

for textbox in textboxes:
Sign up to request clarification or add additional context in comments.

4 Comments

Oh, that's how you'd do it. However, why do they overwrite? What if I wanted to overwrite one another and not create a new one?
Why would you need to overwrite it? You can just change the relevant attributes if you want to alter it.
Well I'm doing recursion so the same statement gets called multiple times over. Rather not have 5 instances of the textbox.
Then, unless you can rearrange your code to create the widget once, you will have to explicitly destroy as Fenikso says
1

There is another reference to your TextCtrl objects so it is no deleted as you would expect. Your panel holds a list of all its children. To delete wxPython widget, you have to explicitly call its Destroy() method. So in your case it would be:

textbox = wx.TextCtrl(panel, -1, "", (10,10), (135,20))
textbox.Destroy()
textbox = wx.TextCtrl(panel, -1, "", (10,40), (135,20))

To be able to access both objects, you either have to do as @jonrsharpe suggests or you can use GetChildren() method. However holding references to all your widgets in your application yourself is preferred method.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.