如何在Tkinter Listbox选择更改时获取回调?

64 投票
3 回答
84695 浏览
提问于 2025-04-16 20:41

在Tkinter中,有很多方法可以在TextEntry小部件内容改变时获取回调,但我还没有找到适合Listbox的小部件的方法(而且我发现的很多事件文档都比较旧或者不完整)。有没有什么办法可以为这个生成一个事件呢?

3 个回答

5

我遇到了一个问题,我需要获取在一个可以多选的列表框中最后选中的项目。如果有人也有同样的问题,这里是我做的:

lastselectionList = []
def onselect(evt):
    # Note here that Tkinter passes an event object to onselect()
    global lastselectionList
    w = evt.widget
    if lastselectionList: #if not empty
    #compare last selectionlist with new list and extract the difference
        changedSelection = set(lastselectionList).symmetric_difference(set(w.curselection()))
        lastselectionList = w.curselection()
    else:
    #if empty, assign current selection
        lastselectionList = w.curselection()
        changedSelection = w.curselection()
    #changedSelection should always be a set with only one entry, therefore we can convert it to a lst and extract first entry
    index = int(list(changedSelection)[0])
    value = w.get(index)
    tkinter.messagebox.showinfo("You selected ", value)
listbox = tk.Listbox(frame,selectmode=tk.MULTIPLE)
listbox.bind('<<ListboxSelect>>', onselect)
listbox.pack()
89

这段代码的意思是……

首先,它定义了一个变量,这个变量用来存储某些信息。接着,它会执行一些操作,比如计算、比较或者是改变这个变量的值。最后,代码会输出结果,可能是显示在屏幕上,或者是保存到文件里。

总的来说,这段代码就是在做一些数据处理的工作,帮助我们完成特定的任务。

def onselect(evt):
    # Note here that Tkinter passes an event object to onselect()
    w = evt.widget
    index = int(w.curselection()[0])
    value = w.get(index)
    print('You selected item %d: "%s"' % (index, value))

lb = Listbox(frame, name='lb')
lb.bind('<<ListboxSelect>>', onselect)
73

你可以绑定到 <<ListboxSelect>> 这个事件。每当你在列表框中选择的内容发生变化时,这个事件就会被触发,无论是通过点击按钮、使用键盘,还是其他任何方式。

下面是一个简单的例子,当你从列表框中选择某个项目时,它会更新一个标签:

import tkinter as tk

root = tk.Tk()
label = tk.Label(root)
listbox = tk.Listbox(root)
label.pack(side="bottom", fill="x")
listbox.pack(side="top", fill="both", expand=True)

listbox.insert("end", "one", "two", "three", "four", "five")

def callback(event):
    selection = event.widget.curselection()
    if selection:
        index = selection[0]
        data = event.widget.get(index)
        label.configure(text=data)
    else:
        label.configure(text="")

listbox.bind("<<ListboxSelect>>", callback)

root.mainloop()

截图

这个事件在列表框的官方文档中有提到。所有预定义的虚拟事件都可以在 绑定文档 中找到。

撰写回答