How to use events and binding to display in result

2020-05-03 10:41发布

问题:

I have fixed this by adding 'exportselection=False' to the listbox line. but if somebody could explain why the [0] is needed in the line 'my_listbox_1.curselection()[0]'. I would be grateful, if not no worries.

from tkinter import *
from tkinter import ttk
my_window = Tk()

frame_for_list1 = Frame(my_window, padx=20, pady=20)
frame_for_list1.grid(row=0, column=0)

frame_for_list2 = Frame(my_window, padx=20, pady=20)
frame_for_list2.grid(row=0, column=1)

my_listbox_1 = Listbox(frame_for_list1, exportselection=False, height='5', width='5')
my_listbox_1.grid(row=0, column=0)

my_listbox_2 = Listbox(frame_for_list2, exportselection=False, height='5', width='5')
my_listbox_2.grid(row=0, column=0)

my_list_1 = ['1', '2', '4', '6']
my_list_2 = ['11', '21', '41', '61']

for item1 in my_list_1:
    my_listbox_1.insert(END, item1)

for item2 in my_list_2:
    my_listbox_2.insert(END, item2)


def select_list1(event=None):
    my_label_list1 = Label(frame_for_list1, text=my_listbox_1.get(my_listbox_1.curselection()[0]))
    my_label_list1.grid(row=1, column=0, pady=10)


my_listbox_1.bind('<<ListboxSelect>>', select_list1)


def select_list2(event=None):
    my_label_list2 = Label(frame_for_list2, text=my_listbox_2.get(my_listbox_2.curselection()[0]))
    my_label_list2.grid(row=1, column=2, pady=10)


my_listbox_2.bind('<<ListboxSelect>>', select_list2)

mainloop()