Home > database >  Get a value by index when Combobox selected and assign the value to "textvariable" in Tkin
Get a value by index when Combobox selected and assign the value to "textvariable" in Tkin

Time:03-26

I'm new to Python and Tkinter. I'm following Python MySQL. How can I pass the ID of a field from a ComboBox to the database? as a guideline to get the value by index.

My Code:

import tkinter as tk
from tkinter import ttk

# --- functions ---

def run_sql(event):
    #print(event)

    index = cb.current()
    # print('index:', index)

    row = c[index]

    print('ID:', row[0])

    print(data.set(row[0]))
    print(cb.set(row[0]))
    
# --- main ---

c = [
  (123, 'A'),
  (124, 'B'),
  (125, 'C'),
]

root = tk.Tk()
data = tk.StringVar()
cb = ttk.Combobox(root, textvariable=data,values=[row[1] for row in c], state='readonly')
cb.pack()
cb.bind("<<ComboboxSelected>>", run_sql)

root.mainloop()

Output:

ID: 123
None
None

I'm looking for a way to get the value of 123 whenever I use data.set(row[0]) or cb.set(row[0]) instead of None.

I appreciate your help.

CodePudding user response:

You could use a wrapper function

def data_set(value):
    data.set(value)
    return [row[1] for row in c if row[0] == value]

But that could return multiple values.

A better solution would be:

def data_set(index):
    data.set(c[index][0])
    return c[index][1]
  • Related