Retrieve Tkinter listbox item by string, not by index
Hendrik van Rooyen
mail at microcorp.co.za
Sat Dec 23 02:13:53 EST 2006
"Kevin Walzer" <kw at codebykevin.com> wrote:
> I'm trying to set the active item in a Tkinter listbox to my
> application's currently-defined default font.
not sure if you can mix fonts in a listbox - the font option
when you create the listbox instance seems to apply globally
to all the lines in the box
> Here's how I get the fonts loaded into the listbox:
>
> self.fonts=list(tkFont.families())
> self.fonts.sort()
>
> for item in self.fonts:
> self.fontlist.insert(END, item) #self.fontlist is the
> ListBox instance
>
Does this actually give you different fonts on each line? or just
a list of available font names, all displayed in the same font?
>
> So far, so good. But I don't know how to set the active selection in the
> listbox to the default font. All the methods for getting or setting a
> selection in the listbox are based on index, not a string. And using
> standard list search methods like this:
>
> if "Courier" in self.fontlist:
> print "list contains", value
> else:
> print value, "not found"
>
> returns an error:
>
> TypeError: cannot concatenate 'str' and 'int' objects
>
> So I'm stuck. Can someone point me in the right direction?
not too sure I understand what you are trying to do - but consider:
idx = self.fontlist.curselection()
this is the index of the selection,
(as controlled by the user's fingers) so:
StringAtCurrSelection = self.fontlist.get(idx)
should be the string containing the text on the selected line
you can use self.fontlist.delete(idx) and
self.fontlist.insert(idx,SomeString) to make changes to the text.
But as to how you change this to display in a different font -
no can tell - don't know how, and not sure if its possible.
Only know that you can use configure to change the font
for all the lines in the box by changing the box's font option...
if, OTOH you are just trying to find where your default
lives in the box, why don't you look for it and remember
the index when you are populating the box?
something like this:
self.idx = 0
for item in self.fonts:
if item == mydefaultfont:
self.defidx = idx
self.fontlist.insert(idx, item)
idx += 1
then you can do whatever with the item that
lives at self.defidx afterwards...
hth - Hendrik
More information about the Python-list
mailing list