Occasionally, you'll need to find a specific widget on a frame or panel without already having a reference to that widget. A common application of this, as shown in chapter 6, is to find the actual menu item object associated with a menu selection (since the event doesn't hold a reference to it). Another use case is when you want an event on one item to change the state of an arbitrary other widget in the system. For example, you may have a button and a menu item that mutually change each other's toggle state. When the button is clicked, you need to get the menu item to toggle it. Listing 8.6 displays a small example taken from chapter 7. In this code, the FindltemByld() method is used to acquire the menu item associated with the ID provided by the event object. The label from that item is used to drive the requested color change.
Listing 8.6 A function which finds an item by ID
def OnColor(self, event):
menubar = self.GetMenuBar()
itemId = event.GetId()
item = menubar.FindltemByld(itemld)
color = item.GetLabel()
In wxPython, there are three methods for finding a subwidget, all of which act similarly. These methods are applicable to any widget that is used as a container, not just frames, but also dialogs and panels. You can look up a subwidget by internal wxPython ID, by the name passed to the constructor in the name argument, or by the text label. The text label is defined as the caption for widgets that have a caption, such as buttons and frames.
The three methods are:
■ wx.FindWindowById(id, parent=None)
■ wx.FindWindowByName(name, parent=None)
■ wx.FindWindowByLabel(label, parent=None)
In all three cases, the parent argument can be used to limit the search to a particular subhierarchy (i.e., it's equivalent to calling the Find method of that argument). Also, FindWindowByName() looks first in the name arguments' if it does not find a match, it calls FindWindowByLabel() to look for a match.
Was this article helpful?