FreddieT
FreddieT

Reputation: 45

Setting an option selected in a combobox as a variable that changes as the option selected in the combobox does

I am trying to set the option selected in the dropdown of a combobox as a variable, however, the label I am using to represent the variable is currently just reading .!combobox . For example if I selected 'Customer 2' from the dropdown , the label would change to customer 2. I may need to use a button to do this but I am unsure how to make that work.

import tkinter as tk
from tkinter import ttk
root = tk.Tk()

ICus = tk.StringVar(root)

ICus.set("Select Customer")

ICustomer = ttk.Combobox( textvariable = ICus, state = 'readonly')
ICustomer['values'] = ("Customer1", "Customer2", "Customer3")
ICustomer.grid(row = 2, column = 2)


label_ICustVar = tk.Label( text= ICustomer)
label_ICustVar.grid(row = 3, column = 3)

To put it simply I want the option selected in the dropdown to be set as a variable that I can use later on in my code. I am quite new to coding so I might be missing something really obvious, any help would be appreciated :)

Upvotes: 2

Views: 3001

Answers (2)

arrethra
arrethra

Reputation: 99

I think for your use, the link provided by a_guest works best, but regarding your example, I think it's best to use the keyword textvariable of the label, i.e.

# note that this is the StringVar ICUS, not the combobox ICUSTOMER.
label_ICustVar = tk.Label( textvariable= ICus) 
label_ICustVar.grid(row = 3, column = 3)

Upvotes: 2

Lafexlos
Lafexlos

Reputation: 7735

You can use <<ComboboxSelected>> event with the get() method.

def update_label(event):
    label_ICustVar.configure(text=ICustomer.get())


ICustomer.bind("<<ComboboxSelected>>", update_label)

update_label method will be fired each time you select an item from combobox dropdown.

Using StringVar() is not necessary with this approach, so you can remove ICus.

Upvotes: 0

Related Questions