Seite 1 von 1

wxPython: ToolBar mit Listen-/Dict-Zugriff auf die Items

Verfasst: Montag 17. September 2007, 08:32
von nkoehring
Hallo...

da ich es bloed und nicht sehr pythonisch finde, wie man bei einer wxPython.ToolBar auf die Items zugreift, hab ich mal eine Klasse geschrieben, die die Toolbar um ein Dictionary "erweitert".

Ich bitte um ausgiebiges Testing fuer alle, die das interessiert. Ich bin noch nicht so sehr dazu gekommen (werd es aber selbstverstaendlich auch nachholen ;) )

So nun hier erstmal der Code:

Code: Alles auswählen

class MyToolBar(wx.ToolBar):
    """ a toolbar with dictionary-like access to its items
    
        Use toolbar["label"] or toolbar[id] to get the item.
        
        To add an item:
        toolbar["label"] = ToolBarToolBase(...) to add an item per label,
        toolbar[id] = ToolBarToolBase(...) to add an item per id...
        You can get an item per ID even if you add it per label and vice versa!
        
        To delete an item simply do
        del toolbar["label"]
        
        You can check the Bar for tools with constructs like
        if "label" in toolbar: ...
        
        Also the normal ToolBar.AddLabelTool(...) way is possible.
        Other add-methods are not implemented, yet!
        
        In methods like "DeleteTool" you can use the label or the id of an item.
    """
    def __init__(self, parent, *args, **kwargs):
        self._itemdict = dict()
        wx.ToolBar.__init__(self, parent, *args, **kwargs)
        
    def __getitem__(self, label_or_id):
        if type(label_or_id) is int:
            for item in self._itemdict.iteritems:
                if item.GetId() == label_or_id: return item
        else:
            return self._itemdict[label_or_id]
        
    def __setitem__(self, tool):
        id = tool.GetId()
        self._itemdict[tool.GetLabel()] = self._itemlist[id]
        self.AddToolItem(tool)
        
    def __delitem__(self, label_or_id): self.DeleteTool(label_or_id)
        
    def __contains__(self, label): return label in self._itemdict
        
    def AddLabelTool(self, id, label, bitmap, bmpDisabled=wx.NullBitmap, kind=0, shortHelp='', longHelp='', clientData=None):
        toolbase = wx.ToolBar.AddLabelTool(self, id, label, bitmap, bmpDisabled, kind, shortHelp, longHelp, clientData)
        self._itemdict[label] = toolbase
        
    def DeleteTool(self, label_or_id):
        if type(label_or_id) is int:
            for item in self._itemdict.itervalues():
                if item.GetId() == label_or_id: tool = item
        else:
            tool = self._itemdict[label_or_id]
        del self._itemdict[tool.GetLabel()]
        wx.ToolBar.DeleteTool(self, tool.GetId())
Angewendet werden kann diese Toolbar zB so wie in diesem Beispiel:
http://paste.pocoo.org/show/3978/