2

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

FreddieT
  • 45
  • 5
  • 1
    What about the [`get`](https://docs.python.org/3.1/library/tkinter.ttk.html#tkinter.ttk.Combobox.get) method of `tkk.Combobox`? It returns you the current value. If you want to have a callback invoked whenever the value changes then take a look at [this question](http://stackoverflow.com/questions/8432419/intercept-event-when-combobox-edited). – a_guest Mar 29 '17 at 09:15
  • 1
    If you use the same value for `textvariable` for the combobox and label, the two will automatically be linked together. This is one of the main reasons why these special variables exist. – Bryan Oakley Mar 29 '17 at 12:08
  • 1
    Hello, Thanks for accepting my answer but [arrethra's answer](http://stackoverflow.com/a/43089901/3134251) seems much better for this case. I think you should accept that one by unaccepting mine first. – Lafexlos Mar 29 '17 at 12:53

2 Answers2

2

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)
arrethra
  • 99
  • 5
0

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.

Lafexlos
  • 7,618
  • 5
  • 38
  • 53