Can I use a tuple for each combobox value in tkinter?

54 views Asked by At

I have tuples of data for each selection in a combobox, but I haven't been able to index it or extract the string numbers, column 2 on the end. I could created lists to separate the values after I extract them with a get(), but is there a away to get each value from the tuple separately? May not be, but I couldn't find it in the docs.

Here is the code:

# Import the required libraries
from tkinter import *
from tkinter import ttk

# Create an instance of tkinter frame or window
win = Tk()

# Set the size of the window
win.geometry("700x350")

# Create a function to clear the combobox
def clear_cb():
   cb.set('')
   
# Define  Tuple
data = [('Value A', 'First', '1.5'), ('Value B', 'Next', '4.5'), ('Value C', 'Last', '5.5')]


# Create a combobox widget
var= StringVar()
cb= ttk.Combobox(win, textvariable= var)
cb['values']= data
cb['state']= 'readonly'
cb.pack(fill='x',padx= 5, pady=5)

selected_value = cb.get()

# Create a button to clear the selected combobox text value
button = Button(win, text= "Clear", command= clear_cb)
button.pack()

win.mainloop()

I want to get the float values that match the selection, ie 1.5 for Value A. The numbers are always the last of each of the tuples, which I thought would allow some index with the get() method, but I couldn't get that to work.

1

There are 1 answers

1
Sohan JS On BEST ANSWER

You can bind a function to the combobox selection event and then extract the corresponding float value from the selected tuple.

You can do this by creating the handle_selection function to handle combobox selection

def handle_selection(event):
    selected_index = cb.current()  # Get the index of the selected item
    selected_tuple = data[selected_index]  # Get the selected tuple
    selected_float = float(selected_tuple[-1])  # Extract the float value from the tuple
    print(selected_float)  # Print the extracted float value

Then Set combobox values to the first element of each tuple. You can do that like this while creating a combobox widget:

cb['values'] = [item[0] for item in data]

Make sure to Bind the handle_selection function to combobox selection event after creating the combobox

cb.bind("<<ComboboxSelected>>", handle_selection)