Tkinter列表框进行选择



我正在尝试创建一个弹出框来选择多个年份。我已经创建了这个框,但我不知道如何制作一个按钮来实际选择多年。目标是将所选内容存储在列表中。

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()

为了澄清,我希望选择2017年和2018年,并使用tkinter-listbox将该选择存储在列表中。

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

按下Start按钮时获取所选值的示例:

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()

基本上,您希望将列表框中所选项目的值添加到列表中。您需要调用listbox小部件上的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()

最新更新