2017-07-17 25 views
0

我在下面有以下示例代碼。有沒有辦法擴展列表框,單擊時顯示100個數字中的10個?當選擇其中一個數字時,列表框會再次隱藏其他數字嗎?Python列表框在點擊後展開和隱藏

from tkinter import * 
 

 
root = Tk() 
 

 
scrollbar = Scrollbar(root) 
 
scrollbar.pack(side=RIGHT, fill=Y) 
 

 
listbox = Listbox(root) 
 
listbox.pack() 
 

 
for i in range(100): 
 
    listbox.insert(END, i) 
 

 
# attach listbox to scrollbar 
 
listbox.config(yscrollcommand=scrollbar.set, height = 1) 
 
scrollbar.config(command=listbox.yview) 
 

 
mainloop()

回答

0

您可以將事件處理程序連接到<Button-1>信號,每一次切換列表框高度:

def listbox_clicked(event): 
    listbox = event.widget 
    if listbox['height'] == 1: 
     listbox.config(height=10) 
    else: 
     listbox.config(height=1) 

listbox.bind('<Button-1>', listbox_clicked) 
+0

這是比我的文章更好的答案,但你需要包括這兩個,使其工作得很好。 –

0

我相信包裝選項會有所幫助。

scrollbar.pack(side=RIGHT, fill=Y, expand=True) 
listbox.pack(fill=Y, expand=True) 
0

非常感謝您的幫助,但我需要的只是一個組合框!