Best way to get the name of a button that called an event?

前端 未结 7 1198
北荒
北荒 2021-01-03 05:26

In the following code (inspired by this snippet), I use a single event handler buttonClick to change the title of the window. Currently, I need to evaluate if t

7条回答
  •  孤独总比滥情好
    2021-01-03 05:53

    I ran into a similar problem: I was generating buttons based on user-supplied data, and I needed the buttons to affect another class, so I needed to pass along information about the buttonclick. What I did was explicitly assign button IDs to each button I generated, then stored information about them in a dictionary to lookup later.

    I would have thought there would be a prettier way to do this, constructing a custom event passing along more information, but all I've seen is the dictionary-lookup method. Also, I keep around a list of the buttons so I can erase all of them when needed.

    Here's a slightly scrubbed code sample of something similar:

    self.buttonDefs = {}
    self.buttons = []
    id_increment = 800
    if (row, col) in self.items:
        for ev in self.items[(row, col)]:
            id_increment += 1
            #### Populate a dict with the event information
            self.buttonDefs[id_increment ] = (row, col, ev['user'])
            ####
            tempBtn = wx.Button(self.sidebar, id_increment , "Choose",
                                (0,50+len(self.buttons)*40), (50,20) )
            self.sidebar.Bind(wx.EVT_BUTTON, self.OnShiftClick, tempBtn)
            self.buttons.append(tempBtn)
    
    def OnShiftClick(self, evt):
        ### Lookup the information from the dict
        row, col, user = self.buttonDefs[evt.GetId()]
        self.WriteToCell(row, col, user)
        self.DrawShiftPicker(row, col)
    

提交回复
热议问题