Jay
Jay

Reputation: 2868

Calculate the amount of items that would fit in the viewable area of a Listbox in Tkinter

I'm having trouble finding out the number of Listbox items that would fit just in the viewable Listbox area, so that you don't need to scroll down. Sorry if this is trivial, I'm having difficulty figuring this one out.

I've wrote a small example to illustrate my problem:

from Tkinter import *
from tkFont import Font

myfont=Font(family='Times', size=12)

a=Listbox(activestyle='dotbox', font=myfont)
a.insert(END, *xrange(100))
a.pack(side='left', fill=BOTH, expand=1)

mainloop()

so now I have a listbox, but only some of its items are visible. How do I figure out how many can I fit without going outside the viewable area? Any insights would be welcome. Thanks!

Upvotes: 1

Views: 191

Answers (2)

Jay
Jay

Reputation: 2868

The size of a tkFont height is stored in the linespace metric, which is accessible via the metrics() method -

myfont.metrics()['linespace']
#returns 19 for myfont as initiated in the question

The height of the Listbox widget is retrievable via winfo_height(). In total -

visible_lines= a.winfo_height()/myfont.metrics()['linespace']

Resource - http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/fonts.html

Upvotes: 2

Terry Jan Reedy
Terry Jan Reedy

Reputation: 19184

Listboxes have an option height, which is the number of lines of text to display. The default is 10. Since you leave the default as is, your box displays 10 lines, containing '0' to '9'. I discovered this by checking http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/index.html, which I use routinely. It only has a few errors.

Upvotes: 0

Related Questions