bob
bob

Reputation: 13

How to make a combobox that binds different methods in python

I want to create multiple combo boxes that have entries in them that will trigger different bind events. For example: Combobox1 = {Mustang, Focus, Tesla} , mustang would have a bind to run method_mustang, focus would have a bind to run the method_focus etc.. all methods that will be created will trigger a different event

Then I want to be able to write a new combo box for trucks that would do something similar. I can successfully create my combobox with the listed items, but I am stuck on how to bind the different items to another method.

Please help.

using code posted in another question: ( no need for the label section but wanted to give something as a reference)

import tkinter as tk
from tkinter import ttk

values = ['mustang', 'focus', 'tesla']
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: 0

Views: 3142

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 386010

Create a single binding that simply maps the values to functions

import tkinter as tk
from tkinter import ttk

values = ['mustang', 'focus', 'tesla']

def method_mustang():
    label.configure(text="mustang selected")
def method_focus():
    label.configure(text="focus selected")
def method_tesla():
    label.configure(text="tesla selected")
def method_unknown():
    label.configure(text="unknown selected")

def handler(event):
    current = combobox.current()
    value = values[current]
    print("current:", current, "value:", value)
    func_map = {
        "mustang": method_mustang,
        "focus": method_focus,
        "tesla": method_tesla
    }
    func = func_map.get(value, method_unknown)
    func()

root = tk.Tk()
combobox = ttk.Combobox(root, values=values)
combobox.bind('<<ComboboxSelected>>', handler)
label = ttk.Label(root, width=20)
combobox.pack(side="top", anchor="w")
label.pack(side="top", fill="x", pady=4)

root.mainloop()

Upvotes: 2

Related Questions