Python - tkinter 如何读取第二个下拉值
Python - tkinter How to read the second drop down values
我正在尝试从下面代码中的第二个下拉选项中读取所选下拉列表的值。 [示例:'Germany'、'France'、'Switzerland']
在这里,我可以使用名为 fun()
的函数读取第一个下拉值
但同样无法读取第二个下拉值。
建议我如何从下面的代码中读取第二个下拉值
这是代码。
import sys
if sys.version_info[0] >= 3:
import tkinter as tk
else:
import Tkinter as tk
class App(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
self.dict = {'Asia': ['Japan', 'China', 'Malaysia'],
'Europe': ['Germany', 'France', 'Switzerland']}
self.variable_a = tk.StringVar(self)
self.variable_b = tk.StringVar(self)
self.variable_a.trace('w', self.update_options)
self.optionmenu_a = tk.OptionMenu(self, self.variable_a, *self.dict.keys(), command=self.fun)
self.optionmenu_b = tk.OptionMenu(self, self.variable_b, '')
self.variable_a.set('Asia')
self.optionmenu_a.pack()
self.optionmenu_b.pack()
self.pack()
def fun(self,value):
print(value)
def update_options(self, *args):
countries = self.dict[self.variable_a.get()]
self.variable_b.set(countries[0])
menu = self.optionmenu_b['menu']
menu.delete(0, 'end')
for country in countries:
menu.add_command(label=country, command=lambda nation=country: self.variable_b.set(nation))
if __name__ == "__main__":
root = tk.Tk()
app = App(root)
app.mainloop()
tkinter 变量有一个 trace
方法,可用于在设置变量时触发回调函数。在您的情况下,将此添加到 __init__
:
self.variable_b.trace('w', self.fun2)
并创建一个新的方法来处理它:
def fun2(self, *args):
print(self.variable_b.get())
我正在尝试从下面代码中的第二个下拉选项中读取所选下拉列表的值。 [示例:'Germany'、'France'、'Switzerland']
在这里,我可以使用名为 fun()
的函数读取第一个下拉值但同样无法读取第二个下拉值。
建议我如何从下面的代码中读取第二个下拉值
这是代码。
import sys
if sys.version_info[0] >= 3:
import tkinter as tk
else:
import Tkinter as tk
class App(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
self.dict = {'Asia': ['Japan', 'China', 'Malaysia'],
'Europe': ['Germany', 'France', 'Switzerland']}
self.variable_a = tk.StringVar(self)
self.variable_b = tk.StringVar(self)
self.variable_a.trace('w', self.update_options)
self.optionmenu_a = tk.OptionMenu(self, self.variable_a, *self.dict.keys(), command=self.fun)
self.optionmenu_b = tk.OptionMenu(self, self.variable_b, '')
self.variable_a.set('Asia')
self.optionmenu_a.pack()
self.optionmenu_b.pack()
self.pack()
def fun(self,value):
print(value)
def update_options(self, *args):
countries = self.dict[self.variable_a.get()]
self.variable_b.set(countries[0])
menu = self.optionmenu_b['menu']
menu.delete(0, 'end')
for country in countries:
menu.add_command(label=country, command=lambda nation=country: self.variable_b.set(nation))
if __name__ == "__main__":
root = tk.Tk()
app = App(root)
app.mainloop()
tkinter 变量有一个 trace
方法,可用于在设置变量时触发回调函数。在您的情况下,将此添加到 __init__
:
self.variable_b.trace('w', self.fun2)
并创建一个新的方法来处理它:
def fun2(self, *args):
print(self.variable_b.get())