繁体   English   中英

Python-Tkinter如何读取第二个下拉值

[英]Python - tkinter How to read the second drop down values

我正在尝试从下面的代码的第二个下拉选项中读取所选下拉列表的值。 [示例:“德国”,“法国”,“瑞士”

在这里,我可以使用名为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())

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM