2013-01-16 269 views
4

我試過在這裏搜索但沒有遇到正確的答案。
我有一個列表框,它是用selection='multiple'設置的。 然後,我嘗試通過代碼name.get(ACTIVE)獲取用戶選擇的所有選項的列表。 問題是,它並不總是獲得我在列表框GUI中突出顯示的所有選項。Python Tkinter多選列表框

如果我強調一個,它會正確地返回。
如果我突出顯示兩個或多個(每個點擊一次),它只返回我選擇的最後一個項目
如果我有多個突出顯示,但點擊不亮選一個,這是我點擊的最後一個返回即使它沒有被強調。

任何幫助都會非常棒。謝謝。我期待代碼能夠帶回突出顯示的內容。

代碼來設置列表框是:

self.rightBT3 = Listbox(Frame1,selectmode='multiple',exportselection=0) 

中檢索的選擇的代碼是:

selection = self.rightBT3.get(ACTIVE) 

這是該應用程序看起來像在行動的截圖,在頂部你可以看到控制檯只註冊了一個選擇(我點擊的最後一個)。

enter image description here

回答

6

看來正確的方式來獲得在Tkinter的列表框中選擇項目列表是使用self.rightBT3.curselection(),返回包含所選行的從零開始的索引元組。然後您可以使用這些索引每行get()

(我沒有實際測試過這雖然)

+0

聽起來不錯@Tharwen謝謝。我曾希望我錯過了一個讓我避免使用'curselection()'的技巧,但我不得不停止懶惰:) – Zenettii

3

我發現上面的解決方案一點點「晦澀」。特別是當我們在這裏處理正在學習工藝或學習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的小部件。