[Tkinter-discuss] Listbox size

Michael Lange klappnase at web.de
Tue Feb 13 18:32:09 EST 2018


Hi,

On Tue, 13 Feb 2018 15:36:55 -0700
Bob van der Poel <bob at mellowood.ca> wrote:

> I know how to find the number of items. Just like you show.
> 
> No, this is not the size of the box. I have maybe 2000 entries. I can
> set the current selection, etc with code like this:
> 
>   self.lb.select_clear(ACTIVE)   # needed to un-hilite existing
> selection self.lb.activate(x)                     # make new item active
>   self.lb.see(x-10)                       # force display from 10
> previous lines
>   self.lb.select_set(x)                 # and select the new item
> 
> If the listbox is 20 lines high, this works perfectly. But, if it is a
> different size, it doesn't center. In my case I don't know the size of
> box, so the "-10" is a not-to-intelligent guess.

you mean, the selected item should be vertically centered in the list?
I believ there is no trivial way to do this, but probably more than one
way with a little tinkering. I set up a simple example with
yview() instead of see(), which seems more appropriate here. I guess this
simple function is certainly not perfect (but maybe it is already good
enough):

######################################################
from Tkinter import *

root=Tk()
l = Listbox(root)
l.pack(side='left', fill='both', expand=1)
s = Scrollbar(root, command=l.yview)
s.pack(side='right', fill='y')
l.configure(yscrollcommand=s.set)

for i in range (2000):
    l.insert('end', 'Item %d' % i)

def test(event):
    i = 597
    wd = event.widget
    wd.selection_clear(0, 'end')
    wd.selection_set(i)
    wd.update_idletasks()
    h1 = wd.winfo_height()
    i1, i2 = wd.nearest(0), wd.nearest(h1)
    wd.yview(i - (i2-i1)/2)

l.bind('<F1>', test)
l.focus()

root.mainloop()
#####################################################

Best regards

Michael


.-.. .. ...- .   .-.. --- -. --.   .- -. -..   .--. .-. --- ... .--. . .-.

	"The combination of a number of things to make existence
	worthwhile." "Yes, the philosophy of 'none,' meaning 'all.'"
		-- Spock and Lincoln, "The Savage Curtain", stardate
		5906.4


More information about the Tkinter-discuss mailing list