I have a data file with chemical names (one name per line) and want to load that into a Tkinter GUI listbox and then be able to select it by clicking on the line. Need some help.
I had to fiddle with this for a while to get it to go. The scrollbar is a little hairy with Tkinter. Here is an example how to do this ...
# loading a Tkinter listbox with data and selecting a data line from Tkinter import * def get_list(event): """ function to read the listbox selection and put the result in a label """ # get line index tuple sel = listbox1.curselection() # get the text seltext = listbox1.get(int(sel)) label1.config(text=seltext) # create the sample data file str1 = """ethyl alcohol ethanol ethyl hydroxide hydroxyethane methyl hydroxymethane ethoxy hydride gin bourbon rum schnaps """ fout = open("chem_data.txt", "w") fout.write(str1) fout.close() # read the data file into a list fin = open("chem_data.txt", "r") chem_list = fin.readlines() fin.close() # strip the trailing newline char chem_list = [chem.rstrip() for chem in chem_list] root = Tk() # create the listbox (note that size is in characters) listbox1 = Listbox(root, width=50, height=6) listbox1.grid(row=0, column=0) # create a vertical scrollbar to the right of the listbox yscroll = Scrollbar(command=listbox1.yview, orient=VERTICAL) yscroll.grid(row=0, column=1, sticky=N+S) listbox1.configure(yscrollcommand=yscroll.set) # label to display selection label1 = Label(root, text='Click on an item in the list') label1.grid(row=1, column=0) # load the listbox with data for item in chem_list: listbox1.insert(END, item) # left mouse click on a list item to display selection listbox1.bind('<ButtonRelease-1>', get_list) root.mainloop()
Oh thank you, that will be a good start into my next project. Is there a way to sort the items in a listbox?
In your case it would be easy to have a sorted listbox by simply loading it with a sorted list. So, replace the lines ...
# load the listbox with data for item in chem_list: listbox1.insert(END, item)
... with ...
# load the listbox with data, sorted case insensitive for item in sorted(chem_list, key=str.lower): listbox1.insert(END, item)
Yeah, that works great. Is there a way to edit a listbox line?
Rather than putting your selected line into Label, put it into Entry. Now you can edit it. Bind the Entry to double mouse click to load it back into Listbox at the index sel you have.