能否双击tkinter列表框选项在Python中调用函数?

11 投票
2 回答
15411 浏览
提问于 2025-04-18 15:41

我有一个列表框和一个关联的“选择”按钮。我希望我的图形界面(GUI)能够实现这样的功能:当用户在列表框中双击任何一个选项时,能够触发这个按钮的命令。我尝试的代码(见下文)在用户选中一个选项后,双击窗口中的任何地方都能正常工作。但我希望它只在用户双击选中的那一行(蓝色高亮的行)时才有效。

有什么好的方法可以做到这一点呢?

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()

2 个回答

3

在绑定的时候,你应该使用一个序列,这个序列要放在< >之间,并且要传递一个函数:

listbox.bind('<Double-Button>', function)
9

root.bind(...) 改成 listbox.bind(...)

撰写回答