Save tkinter dropdown menu choice in a variable to compare

Viewed 6201

I want to use a dropdown menu, after selecting one of the choices a different calculation shall be done. Is there any way to save and compare the selection to use in a variable?

from tkinter import *

root = Tk()
root.title("Calculate")

# Create a Tkinter variable
tkvar = StringVar(root)

# Dictionary with options
choices = sorted({'Good', 'Bad', 'Medium'})
tkvar.set('Good')  # set the default option

popupMenu = OptionMenu(root, tkvar, *choices)
Label(root, text="Please choose").grid(row=2, column=2)
popupMenu.grid(row=3, column=2)
b2 = Button(root, text='Close', command=root.quit)
b2.grid(row=6, column=2)

# on change dropdown value
def change_dropdown(*args):
    global dropdown
    dropdown = str(tkvar.get())
    print(dropdown)
    return dropdown

# link function to change dropdown
tkvar.trace('w', change_dropdown)

if tkvar.get == 'Good':
    print(5)

if tkvar.get == "Bad":
    print(10)

root.mainloop()

If something gets chosen, the change/print function works fine. Just the if functions don't result in any output.

2 Answers

You are linking the change to a function in your case change_dropdown so your if is not in this function put it in and this will work.

Also you need to use tkvar.get() <- brackets.

from tkinter import *

root = Tk()
root.title("Calculate")

# Create a Tkinter variable
tkvar = StringVar(root)

# Dictionary with options
choices = sorted({'Good', 'Bad', 'Medium'})
tkvar.set('Good')  # set the default option

popupMenu = OptionMenu(root, tkvar, *choices)
Label(root, text="Please choose").grid(row=2, column=2)
popupMenu.grid(row=3, column=2)
b2 = Button(root, text='Close', command=root.quit)
b2.grid(row=6, column=2)

# on change dropdown value
def change_dropdown(*args):
    global dropdown
    dropdown = str(tkvar.get())
    print(dropdown)

    if tkvar.get() == 'Good':
        print(5)

    if tkvar.get() == "Bad":
        print(10)

# link function to change dropdown
tkvar.trace('w', change_dropdown)

root.mainloop()

NOTE:

root.mainloop() will block the thread.
Maybe saving your answers in a database.

So this is a widget class I use when I need a dropdown. It calls a function whenever the value has changed. it uses ttk instead of your tk widget but they work together (ttk is more native).

from tkinter import ttk


class Dropdown(ttk.Combobox):
    def __init__(self, master, values, command = None):
        super().__init__(master=master, state="readonly")

        self["values"] = values

        if len(values) == 0:
            raise Exception("Dropdown values cannot be of length 0")

        self.current(0)  # Current value index

        self.command = command
        self.prev_val = self["values"][0]

        self.bind("<<ComboboxSelected>>", self.on_selected)

    @property
    def values(self):
        return self["values"]

    def on_selected(self, event=None):
        # Stops the callback from being called if the value is the same previously
        if self.get() != self.prev_val:
            self.prev_val = self.get()

            if self.command is not None:
                self.command()

    # Returns the index of the current value
    def get_index(self):
        return self["values"].index(self.get())

EDIT: You can test the widget using the following code

import tkinter as tk

def dropdown_callback():
    print("Value:", dropdown.get(), "| Index:", dropdown.get_index(), "| Values:", dropdown.values)

root = tk.Tk()

dropdown = Dropdown(root, ("Value 1", "Value 2", "Value 3"), dropdown_callback)

dropdown.pack()
Related