我想从列表框,tkinter中获取价值

时间:2019-01-14 11:07:50

标签: tkinter google-colaboratory

当我单击listbox中的项目时,我想获取该值并将其打印到标签上。

我试图找出答案,但得到了函数名<<ListboxSelect>>,但未能获得价值。我能做的就是打印出值。

我想要的是当我单击listbox中的项目时,希望将其打印在标签上。

1 个答案:

答案 0 :(得分:0)

下面是您要执行的操作的示例。

import tkinter as tk

root = tk.Tk()

def update(*args):
    a = lbox.curselection() #note a is a tuple containing the line numbers of the selected element counting from 0. 
    print( type(a), a )
    lb_value.set( countrynames[ a[0] ] ) #Update the control variable's value.

countrynames = ('Argentina', 'Australia', 'Belgium', 'Brazil', 'Canada',
                'China', 'Denmark', 'Finland', 'France', 'Greece', 'India')
listCon = tk.StringVar( value=countrynames )
lbox = tk.Listbox(root, listvariable=listCon, height=10, selectmode=tk.SINGLE,)
lbox.grid(row=0, column=0)
lbox.bind('<<ListboxSelect>>', update)

lb_value=tk.StringVar()
lb = tk.Label(root, textvariable=lb_value, bg='yellow')
lb.grid(row=0, column=1)

root.mainloop()

您需要将Listbox所选项目传递到Control variabletextvariable小部件的Label选项将读取该项目。根据列表框中的数据类型,您必须选择要使用的适当类型的控制变量,即StringVar()IntVar()DoubleVar()。我的示例使用StringVar(),因为countryname的内容都是字符串类型。

相关问题