[英]Save tkinter dropdown menu choice in a variable to compare
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.
只是if函数不会导致任何输出。
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. 您正在将更改链接到您的案例
change_dropdown
一个函数,以便将if
不在此函数中,则可以将其放入。
Also you need to use tkvar.get() <- brackets. 另外,您需要使用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()
NOTE: 注意:
root.mainloop()
will block the thread. root.mainloop()
将阻塞线程。
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). 它使用
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())
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.