Tkinter 列表框进行选择

Tkinter Listbox make a selection

我正在尝试创建一个 select 多年的弹出框。我已经创建了框,但我不知道如何制作一个实际 select 多年的按钮。目标是获取 selection 并将其存储在列表中。

from tkinter import *
import pandas as pd
import tkinter as tk

test_years = ["2016", "2017", "2018", "2019"]
root = tk.Tk()
root.title("Test Year Selection")
lb = Listbox(root, selectmode=MULTIPLE, height = len(test_years), width = 50) # create Listbox
for x in test_years: lb.insert(END, x)
lb.pack() # put listbox on window
root.mainloop()

为了澄清,我正在寻找 select 让我们说 2017 年和 2018 年,并使用 tkinter 列表框将 selection 存储在列表中。

如有任何帮助,我们将不胜感激。

当您按下 Start 按钮时获取您 select 的值的示例:

from tkinter import *
# import pandas as pd
import tkinter as tk

def printIt():
    SelectList = lb.curselection()
    print([lb.get(i) for i in SelectList]) # this will print the value you select


test_years = ["2016", "2017", "2018", "2019"]
root = tk.Tk()
root.title("Test Year Selection")
lb = Listbox(root, selectmode=MULTIPLE, height = len(test_years), width = 50) # create Listbox
for x in test_years: lb.insert(END, x)
lb.pack() # put listbox on window

tk.Button(root,text="Start",command=printIt).pack()
root.mainloop()

基本上您想要将列表框的所选项目的值添加到列表中。您需要在列表框小部件上调用 bind() 方法。这是 tkinter listbox

上这个精彩教程的代码
def get_value(event):
    # Function to be called on item click

    # Get the index of selected item using the 'curseselection' method.
    selected = l.curselection()
    if selected: # If item is selected
        print("Selected Item : ",l.get(selected[0])) # print the selected item

# Create a listbox widget
l = Listbox(window)
l.bind('<>',get_value)
l.pack()