[英]wxPython - Widgets With Same Name?
Why does the following code create 2 widgets, and not overwrite each other? 为什么以下代码创建2个小部件,而不是相互覆盖? 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()
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:
There is another reference to your TextCtrl
objects so it is no deleted as you would expect. 还有另一个对
TextCtrl
对象的引用,因此它不会像您期望的那样被删除。 Your panel
holds a list of all its children. 您的
panel
列出其所有孩子的名单。 To delete wxPython widget, you have to explicitly call its Destroy()
method. 要删除wxPython小部件,必须显式调用其
Destroy()
方法。 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. 要能够访问这两个对象,您必须按照@jonrsharpe的建议进行操作,或者您可以使用
GetChildren()
方法。 However holding references to all your widgets in your application yourself is preferred method. 但是,首选在您的应用程序中保留对所有小部件的引用是首选方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.