Python 3.5:使用TKInter下拉菜单中的选项分配多个变量

时间:2017-01-13 02:19:38

标签: python tkinter menu dropdown

感谢furas我有以下ListBox代码:

import tkinter as tk

def on_button():
#     for i, var in enumerate(o_vars):
#         print('OptionMenu {}: {}'.format(i, var.get()))
#     print()

    print('ListBox:', l.curselection())
    for i in l.curselection():
        print('option:', OPTIONS[i])
    print()


# --- main ---

OPTIONS = ["Script 1","Script 2","Script 3","Script 4","Script 5"]

root = tk.Tk()

# --- Listbox ---

tk.Label(root, text='Listbox', bg='#aaa').pack(fill='x')

l = tk.Listbox(root, selectmode='multiple')
l.pack()
l.insert('end', *OPTIONS)

# --- others ---

b = tk.Button(root, text='OK', command=on_button)
b.pack(fill='x')

root.mainloop()

当我运行它时,它会给我以下弹出窗口(如下图所示)。然后我做出选择。

enter image description here

这就是我被困的地方......我想说如果用户选择了Script2打印'脚本2'。如果用户选择了脚本5,则打印“脚本5”。

下面是我尝试过的代码,但它出错了:

if l.curselection() == 'Script1':
    print ('test')
if l.curselection() == 'Script2':
    print ('test2')

TclError:无效的命令名称“.92911768”

另外,如何在“确定”下面添加“退出”按钮?

*非常感谢任何帮助

1 个答案:

答案 0 :(得分:0)

关闭下拉菜单后

OptionMenu只能显示一个选项 - 因此无法选择更多选项。

所以你可以使用这种方法之一:

只有许多OptionMenu您可以选​​择执行脚本的顺序。

示例在一个窗口中显示所有menthod。

enter image description here

import tkinter as tk

# --- functions ---

def on_button():
    for i, var in enumerate(o_vars):
        print('OptionMenu {}: {}'.format(i, var.get()))
    print()

    print('ListBox:', l.curselection())
    for i in l.curselection():
        print('option:', OPTIONS[i])
    print()

    print('ChecboxBox:')
    for i, var in enumerate(cb_vars):
        if var.get():
            print('option:', OPTIONS[i])

# --- main ---

OPTIONS = ["Script 1","Script 2","Script 3","Script 4","Script 5"]

root = tk.Tk()

# --- OptionMenu ---

tk.Label(root, text='OptionMenus', bg='#aaa').pack(fill='x')

o_vars = []

for i in range(3):
    var = tk.StringVar(value='- select -')
    o_vars.append(var)
    o = tk.OptionMenu(root, var, *OPTIONS)
    o.pack()

# --- Listbox ---

tk.Label(root, text='Listbox', bg='#aaa').pack(fill='x')

l = tk.Listbox(root, selectmode='multiple')
l.pack()
l.insert('end', *OPTIONS)

# --- Checkbuttons ---

tk.Label(root, text='Checkbuttons', bg='#aaa').pack(fill='x')

cb_vars = []
for x in OPTIONS:
    var = tk.BooleanVar(value=False)
    cb_vars.append(var)
    c = tk.Checkbutton(root, text=x, variable=var)
    c.pack()

# --- others ---

b = tk.Button(root, text='OK', command=on_button)
b.pack(fill='x')

root.mainloop()

结果:

OptionMenu 1: Script 1
OptionMenu 2: Script 3
OptionMenu 3: Script 5

ListBox: (0, 2, 4)
option: Script 1
option: Script 3
option: Script 5

ChecboxBox:
option: Script 1
option: Script 3
option: Script 5

GitHub:furas/python-examples/tkinter/checkbutton-listbox-optionmenu