Search code examples
pythonwxpython

WxPython, Linking a double click event to specific list box's, opposed to all


I am currently building a GUI, and im using listbox's, the user will double click an item in a list box and the selected item is passed to the code. This works fine, but the problem I am having is that I cannot seem to link the DoubleClick event to a single list box, I just get errors and the program wont run, whenever i try and add an identifier.

The code that works but with no identifer is:

serverlistbox=wx.ListBox(panel1, -1, (300,80), (180,180), serverfilelist, wx.LB_SINGLE)
serverlistbox.SetSelection(0)

self.Bind(wx.EVT_LISTBOX_DCLICK, self.doubleclick)

And the function that handles the data:

 def doubleclick(self,event):
    index = event.GetSelection()
    downloadselect = serverfilelist[index]
    wx.MessageBox('Starting download of ' +str(serverfilelist[index]))

So the EVT is the important bit, i want to link it ONLY to the serverlist box, opposed to all my list box's. Ive tried:

self.Bind(wx.EVT_LISTBOX_DCLICK, self.doubleclick, self.serverlistbox)
self.Bind(wx.EVT_LISTBOX_DCLICK, self.serverlistbox, self.doubleclick)
self.Bind(wx.EVT_LISTBOX_DCLICK, -1, self.doubleclick)

All of the above fail. Please help!!!


Solution

  • your first option should work:

    self.Bind(wx.EVT_LISTBOX_DCLICK, self.doubleclick, self.serverlistbox)
    

    You have some problems that make the code fail: you are indexing serverfilelist in the doubleclick method. However, that list is not accessible inside the method. Probably you should do something like:

    self.serverfilelist = serverfilelist
    self.serverlistbox = wx.ListBox(panel1, -1, (300,80), (180,180), self.serverfilelist, wx.LB_SINGLE)
    self.serverlistbox.SetSelection(0)
    
    self.Bind(wx.EVT_LISTBOX_DCLICK, self.doubleclick, self.serverlistbox)
    
    def doubleclick(self, event):
        index = event.GetSelection()
        downloadselect = self.serverfilelist[index]
        wx.MessageBox('Starting download of %s' % str(downloadselect)
    

    Also if you instantiate serverlistbox as an attribute of the class:

    self.serverlistbox = wx.ListBox(panel1, ....  
    

    then you could call directly self.serverlistbox.GetSelection in the method without using the event.

    I recommend however the use of:

    downloadselect = self.serverlistbox.GetStringSelection()
    

    Then, your method is simplified to:

    def doubleclick(self, event):
        downloadselect = self.serverlistbox.GetStringSelection()
        wx.MessageBox('Starting download of %s' % downloadselect