Hector
Hector

Reputation: 285

How to change multiple Labels based on Combobox selection?

I would like yo know how to have multiple values in different labels depending on a Combobox drop down list selection. For instance, suppose you have one Combobox with the values (car, house, computer) and multiple Labels which reflect different sizes and colors when selecting Combobox. If I select car, I will have for size: big, color: black and so on...

Upvotes: 1

Views: 6656

Answers (2)

A. Rodas
A. Rodas

Reputation: 20679

The Combobox widget generates the virtual event <<ComboboxSelected>>, which you can use to change the options of the labels according to the current value:

import Tkinter as tk
import ttk

values = ['car', 'house', 'computer']
root = tk.Tk()
labels = dict((value, tk.Label(root, text=value)) for value in values)

def handler(event):
    current = combobox.current()
    if current != -1:
        for label in labels.values():
            label.config(relief='flat')
        value = values[current]
        label = labels[value]
        label.config(relief='raised')

combobox = ttk.Combobox(root, values=values)
combobox.bind('<<ComboboxSelected>>', handler)
combobox.pack()
for value in labels:
    labels[value].pack()

root.mainloop()

Upvotes: 6

Bryan Oakley
Bryan Oakley

Reputation: 385970

You can assign a textvariable attribute to a combobox, then put a trace on that variable. The trace will cause a function to be called whenever the value of the combobox changes. In this function you can then set the text for any labels you want.

Upvotes: 3

Related Questions