Reputation: 11275
I am trying to set a Tkinter Listbox value correctly and it isn't working.
self.carrier = Listbox(self)
self.carrier.grid(row=0, column=0)
self.carrier.insert(0, "Verizon")
self.carrier.insert(1, "AT&T")
self.carrier.insert(2, "T-Mobile")
self.carrier.insert(3, "Sprint")
self.carrier.selection_set(self.carrier_num_map(data['carrier']))
def carrier_num_map(self, carrier):
carrier_handles = {
"AT&T": 1,
"T-Mobile": 2,
"Verizon": 0,
"Sprint": 3
}
handle = carrier_handles.get(carrier, None)
return handle
Now the value passed in (in data['carrier']) is correct - I've verified that.
However for some reason, it defaults to the first value in the list (index 0 - Verizon) unless I explicitly click a value.
Why would this be? Shouldn't this code select the value that I want to be active? It looks selected in the widget, but when I try to run code based off of it, it uses the first in the list.
EDIT: Added the listbox. With this current setup, the right value is highlighted upon program start.
Here's a look at the JSON file I'm pulling the data variable from:
{"username": "[email protected]", "password": "mypass", "phone_num": "555-555-1212", "carrier": "Sprint"}
With this setup, Sprint will be highlighted in the listbox on program start, HOWEVER, if I immediately press a button that is supposed to get the carrier value:
carrier = self.carrier.get(ACTIVE)
It gets VERIZON, not, for example, Sprint.
Upvotes: 0
Views: 1184
Reputation: 51
A combination of .selection_set and .see did it for me. It is important to use .see so that the selected value is displayed on the screen if the listbox has a lot of items. Code example below:
import tkinter as tk
root = tk.Tk()
listbox = tk.Listbox(root)
listbox.pack()
listbox.insert(0, 'Hello 1')
listbox.insert(1, 'Hello 2')
listbox.insert(2, 'Hello 3')
listbox.insert(3, 'Hello 4')
listbox.insert(4, 'Hello 11')
listbox.insert(5, 'Hello 12')
listbox.insert(6, 'Hello 13')
listbox.insert(7, 'Hello 14')
listbox.insert(8, 'Hello 21')
listbox.insert(9, 'Hello 22')
listbox.insert(10, 'Hello 23')
listbox.insert(11, 'Hello 24')
listbox.insert(12, 'Hello 31')
listbox.insert(13, 'Hello 32')
listbox.insert(14, 'Hello 33')
listbox.insert(15, 'Hello 34')
listbox.selection_set(12)
listbox.see(12)
root.mainloop()
Upvotes: 1
Reputation: 11275
Not sure why, but adding this code makes it work correctly:
self.carrier.selection_anchor(self.carrier_num_map(data['carrier']))
This is needed to set the actual value correctly apparently for later recall.
self.carrier.selection_set(self.carrier_num_map(data['carrier']))
This is what sets the highlight.
And later on when I need the values
carrier = self.carrier.get(ANCHOR)
Upvotes: 0