问题
I'm wondering if it's possible to somehow store a hidden id along with each entry on a Listbox. The reason for this is that I've got a table which contains a unique id which is from a database (not visible to the user but used to uniquely identify each record) I'm caching the table in memory and using a dictionary keyed on the id
I'd like to create a Listbox which allows me to select one of the records - the displayed text would not be the unique id but a descriptive field (such as 'Name') which is probably unique but this is not enforced and there is no index on it. So for example, If I have:
Id Name
-- ----
2 Rod
5 Jane
15 Freddy
Then selecting Jane
, I would somehow be able to easily access the id 5
My problem is that I can't find a way to associate the unique id (5
) with the selection (Jane
) so that I can easily identify the cached record. I know that I can use control variables but this just gives me a list of all the strings in the list - not what I want. Also, the index (for example on insert) does not seem to be reliable for this purpose.
The only way that I've managed to do this is to have another dictionary mapping the name to the id. For a number of reasons, this is sub-optimal.
Am I missing something here? Is there an easier way of doing this?
回答1:
Keep your ids in a list, then use the .curselection()
index to map these back to the row ids, as long as you keep the ordering the same.
In your example, Jane
is the second choice in your list, so if selected .curselection()
returns 1
. If you have a rowids
list in the same order, rowids[1]
will be 5
:
>>> rowids = [2, 5, 15]
>>> rowids[listbox.curselection()]
5
Slightly more efficient than mapping names to rowids in a dictionary.
回答2:
If you use the ttk.Treeview widget instead of a Listbox, you can store the id in an invisible column.
来源:https://stackoverflow.com/questions/10751735/hidden-id-on-tkinter-listbox