Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I double-click a tkinter Listbox option to invoke function in Python?

I have a Listbox with an associated "Select" button. I want my GUI such that a double-click on any Listbox value invokes this button's command. My attempt (below) works when an option is selected and the user double-clicks ANYWHERE in the window. I want it to work only when the selection itself (blue highlighted row) is being double-clicked.

What is the best way to do this?

from tkinter import *

def func1():
    print("in func1")

def func2():
    print("in func2")

def selection():
    try:
        dictionary[listbox.selection_get()]()
    except:
        pass

root = Tk()

frame = Frame(root)
frame.pack()

dictionary = {"1":func1, "2":func2}

items = StringVar(value=tuple(sorted(dictionary.keys())))

listbox = Listbox(frame, listvariable=items, width=15, height=5)
listbox.grid(column=0, row=2, rowspan=6, sticky=("n", "w", "e", "s"))
listbox.focus()

selectButton = Button(frame, text='Select', underline = 0, command=selection)
selectButton.grid(column=2, row=4, sticky="e", padx=50, pady=50)

root.bind('<Double-1>', lambda x: selectButton.invoke())

root.mainloop()
like image 913
Big Sharpie Avatar asked Aug 01 '14 20:08

Big Sharpie


2 Answers

Change root.bind(...) to listbox.bind(...)

like image 137
Bryan Oakley Avatar answered Nov 09 '22 09:11

Bryan Oakley


In binding you should use sequence which should be passes inside < > and pass function:

listbox.bind('<Double-Button>', function)
like image 38
Tolqinbek Isoqov Avatar answered Nov 09 '22 10:11

Tolqinbek Isoqov