我發現上面的解決方案一點點「晦澀」。特別是當我們在這裏處理正在學習工藝或學習python/tkinter的程序員時。
我想出了一個更具解釋性的解決方案,這是以下內容。我希望這對你更好。
#-*- coding: utf-8 -*-
# Python version 3.4
# The use of the ttk module is optional, you can use regular tkinter widgets
from tkinter import *
from tkinter import ttk
main = Tk()
main.title("Multiple Choice Listbox")
main.geometry("+50+150")
frame = ttk.Frame(main, padding=(3, 3, 12, 12))
frame.grid(column=0, row=0, sticky=(N, S, E, W))
valores = StringVar()
valores.set("Carro Coche Moto Bici Triciclo Patineta Patin Patines Lancha Patrullas")
lstbox = Listbox(frame, listvariable=valores, selectmode=MULTIPLE, width=20, height=10)
lstbox.grid(column=0, row=0, columnspan=2)
def select():
reslist = list()
seleccion = lstbox.curselection()
for i in seleccion:
entrada = lstbox.get(i)
reslist.append(entrada)
for val in reslist:
print(val)
btn = ttk.Button(frame, text="Choices", command=select)
btn.grid(column=1, row=1)
main.mainloop()
請注意,使用催產素的TTK主題的部件完全是可選的。您可以使用普通tkinter的小部件。
聽起來不錯@Tharwen謝謝。我曾希望我錯過了一個讓我避免使用'curselection()'的技巧,但我不得不停止懶惰:) – Zenettii