【发布时间】:2017-05-28 08:11:24
【问题描述】:
感谢 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()
当我运行它时,它会给我以下弹出窗口(如下图所示)。然后我做出我的选择。
这是我卡住的地方...我想说如果用户选择了 Script2 打印“脚本 2”。如果用户选择了脚本 5,则打印“脚本 5”。
下面是我试过但出错的代码:
if l.curselection() == 'Script1':
print ('test')
if l.curselection() == 'Script2':
print ('test2')
TclError: 无效的命令名“.92911768”
另外,如何在“确定”下方添加“退出”按钮?
*非常感谢任何帮助
【问题讨论】:
-
当您关闭下拉菜单时,此小部件只能显示一个选项 - 这就是您只能选择一个选项的原因。如果您必须同时选择更多选项,请使用Listbox。
-
顺便说一句:我们使用
CamelCase类名称 - 即。SimpleFormApp使代码更具可读性 - PEP 8 -- Style Guide for Python Code -
永远不要更改问题的文本!!! - 在下方添加新信息。现在你的问题对其他用户毫无用处。
-
如果您有新问题,请创建新问题!!!
-
解决问题的旧方法 - 使用
print()查看变量中的内容以及执行的代码部分。所以使用print(l.curselection())看看你会得到什么。
标签: python tkinter menu dropdown