2016-04-18 70 views
-1

嗨〜我在python gui中使用tkinter。我的代碼是列表框wdiget。我想添加與列表框小部件的過濾器。 但我不知道它沒有。我該如何做才能做到這一點。 我想添加過濾器..我不知道這樣做.. 請幫我。我不知道make search_data()。如何在tkiter中添加過濾器小部件?

from tkinter import * 

def search_data(): 
    print('d') 


root=Tk() 
dd = Frame(root, borderwidth=0) 
# create the entry widget 
entry_value = StringVar() 
entry = Entry(dd, textvariable=entry_value) 
entry.pack(side=LEFT) # where ever you want it 
Button(dd, text = 'search ', command = search_data).pack(side=LEFT)  
dd.pack() 

scrollbar=Scrollbar(root) 
scrollbar.pack(side=RIGHT,fill=Y) 
mylist=Listbox(root,yscrollcommand=scrollbar.set, width=100, height=15) 
for line in range(100): 
    mylist.insert(END,"This is line number " + str(line)) 
mylist.pack(side=LEFT,fill=BOTH) 
scrollbar.config(command=mylist.yview)  
mainloop() 

回答

0

要有一個過濾器,你需要在你的GUI中有「東西」讓你的用戶輸入過濾器模式。

例如一個Entry小部件,因爲我們正在談論tkinter。

僞代碼

# do your imports 

# create the entry widget 
entry_value = StringVar() 
entry = Entry(root, textvariable=entry_value) 
entry.pack() # where ever you want it 

#now add your list box 

#add e.g. a button to apply your filter 

def filter_data(): 
    # ... iterate over your data, check if your filter applies and decide how to proceed 

的按鈕:檢查回調和數據結構從文檔,看看如何可以這樣做。

編輯數據的1

儲存:

您直接將項目添加到列表中。

mylist.insert(END,"This is line number " + str(line))

這是顯示數據的方式 - 是的。 這是可維護的代碼嗎?不是真的。

要過濾顯示的數據,我建議使用一些refresh函數訪問存儲的數據以顯示。

如何實現這一目標? 通常,應該有某種數組,字典或類似的東西來存儲數據。也可以是讀取和解析數據的文件。

讓我給你根據你的代碼的例子:

  • 你有一個僞產生for i in range(0,100):

    我想你以後會在讀取文件基於您的變量的命名,但將其改爲常用的i用作最常用循環中的索引。

    在您的代碼中,您可以將數據存儲在列表中。

raw_data = range(0,100) 
actual_data = raw_data # this will be used from now on inside your refresh 
def refresh(): 
    # clean your listbox 

    # iterate over the data 
    for line in actual_data: 
     #add it now to the listbox 

def filter(): 
    # get your filter pattern first 
    # we have a string var, so use "get()" 
    filter_pattern = entry_value.get() 
    # now create a new list 
    actual_data = [] 

    # iterate over raw data, check if data matches filter 
    # if it does, append it to actual_data 

    # call refresh now 
    refresh() 

是的,我知道有很多在上面的示例代碼丟失。

爲什麼? 我故意留下了大部分代碼。正如Bryan已經提到的,SO是而不是代碼寫入服務。說實話,我想你沒有任何編程經驗。讓我直說,這不是一件壞事,,但它看起來並不像你做了很多研究。閱讀文檔,教程,自己嘗試。這將幫助您創建代碼,軟件等。獨自一人可能有助於某些編程問題,但不能成爲程序員。這是一個決定,沒有人可以強迫你成爲。

+0

_「你需要用......」 - 什麼是「......」? –

+0

更新了它 - 希望這可以讓它更容易理解。 「sth」應該是「something」 – R4PH43L

+0

的縮寫,謝謝你的回答。但我的英文不好...你是否顯示代碼..不是seudo代碼.. –