Thanks to furas I have the following code for 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()
When I run it, it gives me the following pop-up (image shown below). I then make my selections.
This is where I am stuck... I want to say if user selected Script2 print 'script 2'. If user selected script 5, print 'script 5'.
Below is the code I tried but it errored out:
if l.curselection() == 'Script1':
print ('test')
if l.curselection() == 'Script2':
print ('test2')
TclError: invalid command name ".92911768"
Also, how do I add a "Quit" button below "OK"?
*Any help is greatly appreciated
解决方案
OptionMenu after closing dropdown menu can display only one option - so it can't select more options.
So you can use one of this method:
Listbox which can select many elements
Only with many OptionMenu you can select in which order execute scripts.
Example shows all menthods in one window.
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()
Result:
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