Home > front end >  Python tkinter/ttk Combobox- I'm wanting each option in a Python ttk-combobox to display 1 list
Python tkinter/ttk Combobox- I'm wanting each option in a Python ttk-combobox to display 1 list

Time:02-03

database_list = ["Movies", "Movies", "Games", "Music", "Games", "Music"]

id_list = [0,1,2,3,4,5]

my_combobox = ttk.Combobox(root, **values=database_list**)
my_combobox.grid(row=1, column=1)

I want the user to see "Movies", "Movies", "Games", "Music", "Games", "Music" shown in the dropbox physically.. but when the user submits the form, I want the form to send the id values from the 2nd list instead of their string/face values.. the same way HTML dropboxes work..

Is there an attribute for a ttk combobox that I'm not seeing in the docs?

I tried generating a list of all of the configure options for a ttk combobox but I'm not seeing one that seems to fit what I'm doing.

options = my_combobox.configure()
for option in options:
    print(option)

CodePudding user response:

By using zip function makes it easy to also zip more than two lists.

code:

import tkinter as tk
from tkinter import ttk


root = tk.Tk()

database_list = ["Movies", "Movies", "Games", "Music", "Games", "Music"]
id_list = [0,1,2,3,4,5]

x = list(zip(id_list, database_list))
 
my_combobox = ttk.Combobox(root, values=x, state="readonly")
my_combobox.grid(row=1, column=1)
my_combobox.current(0)

def submit():       
    print(f"{my_combobox.get()}")

tk.Button(root, text="Submit", command=submit).grid(row=1, column=2)

root.mainloop()

CodePudding user response:

You can use .current() function of Combobox to get the index of the selected value, and then use this index to get the ID from id_list.

Below is a simple example:

import tkinter as tk
from tkinter import ttk

database_list = ["Movies", "Movies", "Games", "Music", "Games", "Music"]
id_list = [0,1,2,3,4,5]

root = tk.Tk()

my_combo = ttk.Combobox(root, values=database_list, state="readonly")
my_combo.grid(row=1, column=1)

def submit():
    idx = my_combo.current()
    if idx >= 0:
        id_value = id_list[idx]
        print(f"{my_combo.get()} -> {id_value}")

tk.Button(root, text="Submit", command=submit).grid(row=1, column=2)

root.mainloop()
  • Related