perl - How to get the "width" of a string to be used in a Tkx label -
i making simple application using perl tkx , allow user select directory. rather using text wrapping or stretching box ridiculous length show whole directory name, if name long truncate , append "..." end.
the problem width of label defined arbitrary value (like 40). if value measurement of how many characters label fit truncate string 37 , append "..." doesn't seem case.
does know -width
of label using perl tkx measurement of? how can find amount of -width
units string take can figure out appropriate point truncate it?
edit:
i found answer in tcl manual:
database class: width specifies desired width label. if image or bitmap being displayed in label value in screen units (i.e. of forms acceptable tk_getpixels); text in characters.
if option isn't specified, label's desired width computed size of image or bitmap or text being displayed in it.
this should mean width of 40 truncate text should have truncate string 37 characters , add "...".
i tested filling label "m"s. used letter "m" because typically widest character (see here). wrote code truncate @ 37 "m"s , add "..." end, "m"s seem overflow past end of label after 24 "m"s.
this means not safe assume stretches label fit 40 of widest character... question still unanswered.
how can determine "width" of string can truncate appropriately?
edit2:
i found workaround still not solution looking for. if change text on label fixed-width font work properly. doesn't nice though solution works non-fixed-width fonts.
when docs -width
labels interpreted number of characters it's using average width of character rather maximum width. discovered, when using fixed-width fonts can work in characters , come out nicely. when using variable-width fonts things difficult because there's no fixed relationship between characters , pixels.
you need work in consistent units (i.e. pixels) , shorten text until fits -- preferably initial guess keep code fast. can label width in pixels via winfo reqwidth
, text width in pixels (for particular font) font measure
.
use strict; use warnings; use tkx; tkx::package_require('tile'); $text; $mw = tkx::widget->new('.'); $label = $mw->new_ttk__label(-width => 10, -textvariable => \$text); tkx::pack($label, -side => 'left'); $text = limit_text($label, 'abcdefghijklmnopqrstuvwxyz'); tkx::mainloop; sub limit_text { $label = shift; $text = shift; $font = $label->cget('-font') || 'tkdefaultfont'; $label_width = $label->g_winfo_reqwidth; $text_width = tkx::font_measure($font, $text); $i = int length($text) * ($label_width / $text_width); while ($text_width > $label_width) { $text = substr($text, 0, --$i) . '...'; $text_width = tkx::font_measure($font, $text); } return $text; }
Comments
Post a Comment