如何解决Tkinter嵌套函数中combo box下拉选择框取值不更新问题
问题根因
你代码的核心问题是变量作用域匹配错误:
dropDownBoxTempValue是tempConverter函数的内部局部变量,不属于全局作用域storedTemperature函数中使用global关键字声明的变量会去全局作用域查找,根本找不到你定义的dropDownBoxTempValue,所以下拉选择触发的赋值操作完全没有生效,convert函数读取到的永远是初始赋值的Celsius
最简修复方案
你完全不需要额外维护dropDownBoxTempValue变量和storedTemperature回调函数,OptionMenu绑定的variable本身就是StringVar类型,直接在转换函数中读取它的当前值即可,修改后的完整代码如下:
from tkinter import * from tkinter import ttk def tempConverter(): temperatureConverter = Tk() temperatureConverter.geometry('650x650') def convert(): # 直接读取OptionMenu绑定的StringVar当前值即可 dropDownBoxTempValue = variable.get() temperature = enterTemperature.get() if dropDownBoxTempValue == 'Celsius': f = (float(temperature) * 9 / 5) + 32 temperatureLabel['text'] = f'{round(f, 2)}° Fahrenheit' k = (float(temperature)) + 273.15 temperatureLabel2['text'] = f'{round(k, 2)}° Kelvin' elif dropDownBoxTempValue == 'Fahrenheit': c = (float(temperature) - 32) * 5 / 9 temperatureLabel['text'] = f'{round(c, 2)}° Celsius' k = (float(temperature) - 32) * 5 / 9 + 273.15 temperatureLabel2['text'] = f'{round(k, 2)}° Kelvin' elif dropDownBoxTempValue == 'Kelvin': c = (float(temperature) - 273.15) temperatureLabel['text'] = f'{round(c, 2)}° Celsius' f = (float(temperature) - 273.15) * 9 / 5 + 32 temperatureLabel2['text'] = f'{round(f, 2)}° Fahrenheit' inputNumber = StringVar() variable = StringVar() enterTemperature = Entry(temperatureConverter, textvariable=inputNumber, font='Helvetica 14') enterTemperature.pack() temperatureLabel = Label(temperatureConverter, text="") temperatureLabel.pack() temperatureLabel2 = Label(temperatureConverter, text="") temperatureLabel2.pack() dropDownList = ["Celsius", "Fahrenheit", "Kelvin"] # 去掉多余的command回调 temperaturedropDown = OptionMenu(temperatureConverter, variable, *dropDownList) temperaturedropDown.pack() variable.set(dropDownList[0]) convertButton = Button(temperatureConverter, text="CONVERT", command=convert) convertButton.pack() temperatureConverter.mainloop() tempConverter()
保留原有结构的修改方法
如果不想删除你原来写的storedTemperature回调和单独的存储变量,只需要把storedTemperature里的global关键字换成nonlocal即可,nonlocal的作用是声明当前变量引用外层嵌套函数的局部变量:
def storedTemperature(setTemp): nonlocal dropDownBoxTempValue dropDownBoxTempValue = setTemp
内容的提问来源于stack exchange,提问作者Ryeux
相关产品推荐
相关产品推荐

