列表框,如何获取所选元素的值?

Listbox, how to get the value of chosen element?

我正在 Tkinter 中创建一个 GUI,并且我刚刚开始使用列表框,我该如何为我的项目赋值?那可能吗?例如,如果我的列表框有 'Press here to print nr 7'、'Press here to print nr 45'、'Press here to print nr 112' 等项目,那么我希望第一个项目的值为 7,第二个项目的值为 45,依此类推,就像您一样可以使用单选按钮。

当您单击项目时,

listbox 默认不会 运行 任何功能。您必须 assign/bind 事件 '<<ListboxSelect>>' 带有单击后应执行的函数名称。在此函数中,您可以从 listbox

中进行选择
import tkinter as tk

# --- function ---

def on_selection(event):
    # here you can get selected element

    print('previous:', listbox.get('active'))
    print(' current:', listbox.get(listbox.curselection()))

    # or using `event`

    #print('event:', event)
    #print('widget:', event.widget)
    print('(event) previous:', event.widget.get('active'))
    print('(event)  current:', event.widget.get(event.widget.curselection()))

    print('---')

# --- main ---

root = tk.Tk()

listbox = tk.Listbox(root)
listbox.pack()

listbox.insert(1, 'Hello 1')
listbox.insert(2, 'Hello 2')
listbox.insert(3, 'Hello 3')
listbox.insert(4, 'Hello 4')

listbox.bind('<<ListboxSelect>>', on_selection)

root.mainloop()