将tkinter下拉菜单选项保存在变量中以进行比较

时间:2019-06-10 11:20:50

标签: python tkinter

我想使用一个下拉菜单,在选择了一个选项之后,应执行不同的计算。有什么方法可以保存和比较要在变量中使用的选择?

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函数不会导致任何输出。

2 个答案:

答案 0 :(得分:0)

您要根据情况change_dropdown将更改链接到一个函数,因此您的if不在此函数中,因此可以使用。

还需要使用tkvar.get()<-方括号。

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

注意:

root.mainloop()将阻塞线程。
也许将答案保存在数据库中。

答案 1 :(得分:0)

所以这是我需要下拉菜单时使用的小部件类。每当值更改时,它将调用一个函数。它使用ttk而非您的tk小部件,但它们可以协同工作(ttk更本地化)。

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

编辑:您可以使用以下代码测试窗口小部件

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