MOHAMMED ISMAIL MOHAMMED ISMAIL - 1 month ago 6
Python Question

How to Display selected values from a dictionary to a listbox

I'm busy making a program with a search function where a person will enter for example subject "Information Systems" in a GUI Tk entry, and i want it to display on those records which has Information systems. Here is some code:

StudentList[[Tom,Information systems],[John,Computers]]


So basically if I type Information systems, it must show in my listbox:
"Tom, Information Systems"

How do i make this search function work?
This is what i have tried

for i in students:
if viewcode == True:
lb1.insert(END,str(i))

Answer

This does roughly what you are looking for. Enter your search term in the Entry box and press Return. It will then populate the Listbox with any matching entries from the student list.

from tkinter import *

student_list = [['Tom','Information Systems'],['John','Computers']]


class App(Frame):
    def __init__(self,parent=None,**kw):
        Frame.__init__(self,master=parent,**kw)
        self.searchValue = StringVar()

        self.searchBox = Entry(self,textvariable=self.searchValue)
        self.searchBox.pack()
        self.resultList = Listbox(self)
        self.resultList.pack()

        self.searchBox.bind('<Return>',self.update)

    def update(self,e):
        print("*")
        self.resultList.delete(0,END)
        searchkey = self.searchValue.get()
        for student in student_list:
            if searchkey == student[0]:
                self.resultList.insert(END,str(student))
            elif searchkey == student[1]:
                self.resultList.insert(END,str(student))

if __name__ == '__main__':
    root = Tk()
    app = App(root)
    app.pack()
    root.mainloop()