代码之家  ›  专栏  ›  技术社区  ›  Tech Learner

在tkinter中使用optionmenu小部件时出错

  •  2
  • Tech Learner  · 技术社区  · 9 年前

    我用python 2.7编写了一段代码,实现了“optionmenu”小部件。我面临一个问题,我在元组中给出了六个值,但当我选择另一个选项而不是“Gmail”时,我在下拉列表中只看到五个值。谁能告诉我我的错误吗?

    from Tkinter import *
    import ttk
    
    root = Tk()
    
    choices = ("Gmail", "Outlook/Hotmail", "Yahoo", "Comcast", "AT&T", "Verizon")
    dropdown_var = StringVar()
    dropdown_var.set(choices[0]) # set default value
    
    def data(*args):
        value = dropdown_var.get()
        print(value)
    
    l = ttk.Label(root, text="Select your e-mail provider : ")
    l.pack(side="left")
    
    option = ttk.OptionMenu(root, dropdown_var, *choices)
    option.pack(side="left", padx=10, pady=10)
    
    b = ttk.Button(root, text="Click", command=data)
    b.pack(side="bottom")
    
    root.mainloop()
    
    1 回复  |  直到 9 年前
        1
  •  1
  •   PRMoureu    9 年前

    您面临的问题与您定义 OptionMenu 小装置。

    事实上,它与tkinter选项菜单不同,因为您在声明中设置了默认值。因此,当您解压缩这些值时,第一个索引 "Gmail" 被视为 default

    (此外,您不需要设置 dropdown_var

    choices = ("Gmail", "Outlook/Hotmail", "Yahoo", "Comcast", "AT&T", "Verizon")
    dropdown_var = StringVar()
    
    def data(*args):
        value = dropdown_var.get()
        print value # no bracket for python2
    
    l = ttk.Label(root, text="Select your e-mail provider : ")
    l.pack(side="left")
    
    # the 3rd parameter is the default value    
    option = ttk.OptionMenu(root, dropdown_var, choices[0], *choices) 
    option.pack(side="left", padx=10, pady=10)