中选择的内容更改

中选择的内容更改

本文介绍了根据在另一个 OptionMenu 中选择的内容更改 OptionMenu的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试制作两个 OptionMenu,其中第二个将根据第一个 OptionMenu 中选择的内容动态更新.

I am currently trying to make two OptionMenus, where the second will be updated dynamically based on what is selected in the first OptionMenu.

例如,我想用列表

[North America, Europe, Asia]

  • 如果选择了 Asia,则 OptionMenu_B 将更改为类似于 [Japan, China, Malasia] 的内容.
  • 如果选择了Europe,那么它将更改为例如[Germany, France, Switzerland].
    • If Asia is selected, then OptionMenu_B will change to something like [Japan, China, Malasia].
    • If Europe is selected, then it will change to [Germany, France, Switzerland] for example.
    • 我可以创建两个 OptionMenu,但无法根据 OptionMenu_A 的状态更新 OptionMenu_B.

      I am able to make two OptionMenus but can't get OptionMenu_B to update based on OptionMenu_A's status.

      有没有人能善意地表明这种事情是否可能?

      Would anybody be kind enough to show if such thing is possible?

      推荐答案

      是的,这是可能的.使用 StringVar.trace 您可以检查第一个选项何时更改.然后删除第二个 OptionMenu 的所有选项并用相应的选项填充它.如果你有一个像字典这样的数据结构,那么映射对应关系就很容易了:

      Yes, it is possible. With StringVar.trace you can check when the first option has been changed. Then delete all the options of the second OptionMenu and populate it with the corresponding options. If you have a data structure like a dictionary behind this, it can be very easy to map the correspondences:

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

      这篇关于根据在另一个 OptionMenu 中选择的内容更改 OptionMenu的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 16:32