📌  相关文章
📜  如何从 tkinter 的列表框中获取选定的值?(1)

📅  最后修改于: 2023-12-03 15:37:55.025000             🧑  作者: Mango

如何从 tkinter 的列表框中获取选定的值?

在 tkinter 中,使用 Listbox 可以创建一个列表框,内部可以包含多个选项。如果需要获取用户在列表框中选定的值,有多种方法可供选择。下面介绍其中两种常用方法。

方法一:使用索引获取选定的值
from tkinter import *

def get_selected_value():
    selected_index = listbox.curselection()
    if selected_index:
        selected_value = listbox.get(selected_index)
        print(selected_value)
    else:
        print("请先选择一个选项!")

root = Tk()

listbox = Listbox(root)
listbox.pack()

for item in ["Python", "Java", "C++", "JavaScript", "PHP", "Ruby", "Kotlin"]:
    listbox.insert(END, item)
    
button = Button(root, text="获取选定的值", command=get_selected_value)
button.pack()

root.mainloop()

这个示例程序中,使用 curselection() 方法获取用户选择的选项的索引值,如果索引值存在则使用 get() 方法获取对应的选项值。如果索引值不存在,说明用户没有选中任何选项,程序输出提示信息。

方法二:使用绑定方法获取选定的值
from tkinter import *

def get_selected_value(event):
    selected_value = listbox.get(ACTIVE)
    print(selected_value)

root = Tk()

listbox = Listbox(root)
listbox.pack()

for item in ["Python", "Java", "C++", "JavaScript", "PHP", "Ruby", "Kotlin"]:
    listbox.insert(END, item)
    
listbox.bind("<<ListboxSelect>>", get_selected_value)

root.mainloop()

这个示例程序中,使用 bind() 方法将 get_selected_value() 方法与 Listbox<<ListboxSelect>> 事件绑定,在用户选择列表框中的选项时,该方法将获取选项的值并输出到控制台。

以上是两种常用方法,具体使用可以根据实际需要选择。在获取选定的值时, 则可以根据情况进行后续的处理。