当 Tkinter 列表框选择更改时获得回调? [英] Getting a callback when a Tkinter Listbox selection is changed?

查看:33
本文介绍了当 Tkinter 列表框选择更改时获得回调?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Tkinter 中更改 TextEntry 小部件时,有多种获取回调的方法,但我还没有找到用于 Listbox's(它没有帮助我能找到的大部分事件文档是旧的或不完整的).有没有办法为此生成事件?

There are a number of ways of getting callbacks when Text or Entry widgets are changed in Tkinter, but I haven't found one for Listbox's (it doesn't help that much of the event documentation I can find is old or incomplete). Is there some way of generating an event for this?

推荐答案

您可以绑定到 <<> 事件.在选择变化时,将生成此事件,无论它是否从按钮,通过键盘或任何其他方法都会从按钮中更改.

You can bind to the <<ListboxSelect>> event. This event will be generated whenever the selection changes, whether it changes from a button click, via the keyboard, or any other method.

这里有一个简单的例子,当你从列表框中选择一些东西时,它会更新一个标签:

Here's a simple example which updates a label whenever you select something from the listbox:

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

此事件在规范的列表框手册页中提及.所有预定义的虚拟事件都可以在 绑定手册页.

This event is mentioned in the canonical man page for listbox. All predefined virtual events can be found on the bind man page.

这篇关于当 Tkinter 列表框选择更改时获得回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆