0

I am trying to create a pop-up box to select multiple years. I have the box created but I cannot figure out how to make a button to actually select multiple years. The goal is to take that selection and store it in a list.

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

To clarify I am looking to select lets say 2017 and 2018 and have that selection stored in a list using tkinter listbox.

Any assistance would be greatly appreciated.

3

2 Answers 2

2

A example to get the value you select when you press the Start button:

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()
Sign up to request clarification or add additional context in comments.

Comments

1

Basically you want to add the value of selected item of listbox to a list. you need to call bind() method on the listbox widget. here is the code from this amazing tutorial on 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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.