Tk 如何计算小部件大小? [英] How does Tk calculate widget size?

查看:37
本文介绍了Tk 如何计算小部件大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  • 我想知道计算小部件的确切公式是什么合身尺寸.

我想应用这些知识来根据小部件的大小动态调整小部件文本的字体大小.

I want to apply that knowledge to dynamically resizing the font of a widget's text, based on the widget's size.

推荐答案

Tk GUI 通常相反;小部件重塑以适应其内容以及定义的任何边距和边框空间.(在 Ttk 小部件中,样式指定了许多这些值.)然后将一般请求的大小作为建议输入几何管理引擎.小部件实际获得的大小取决于它的其他小部件的环境以及它直接想要的东西,而其规则取决于所使用的几何管理器;gridpackplace 在内部都有完全不同的规则引擎(实际上,grid 是一个复杂的约束满足求解器).

Tk GUIs usually work the other way round; the widgets reshape to accommodate their content plus whatever margin and border space is defined. (In Ttk widgets, the style specifies many of those values.) That general requested size is then fed as a suggestion into the geometry management engine. What size a widget actually gets depends on its environment of other widgets as well as what it directly wants, and the rules for that depend on the geometry manager being used; grid, pack and place all have quite different rule engines internally (indeed, grid is a complex constraint satisfaction solver).

反过来工作更容易.如果你知道你有多少空间,你可以使用font measure来计算你的文本在特定的字体和大小是否适合水平;对于多条线(您不会说这是否是您的场景),您需要单独测量每条线.在垂直方向上,您通常只需从 font metrics 中获取整体高度,然后乘以所涉及的文本行数;无论如何,这就是字体渲染引擎在内部有效地执行的操作.

It is easier to work from the other way round. If you know how much space you have, you can use font measure to work out whether your text in a particular font and size will fit horizontally; with multiple lines (you don't say if this your scenario or not) you need to measure each line individually. Vertically, you usually just get the overall height from font metrics and multiply by the number of lines of text involved; that's what the font rendering engine effectively does internally anyway.

这是一个帮助程序,展示了如何在单行情况下执行此操作.

Here's a helper procedure that shows how to do it in the single line case.

proc findFontForLine {basefont maxX maxY text} {
    for {set size 2} {$size < 72} {incr size} {
        set testfont [lreplace $basefont 1 1 $size]
        if {[font measure $testfont $text] > $maxX} break
        if {[font metrics $testfont -linespace] > $maxY} break
        set font $testfont
    }
    if {[info exists font]} {
        return $font
    }
    error "could not find reasonable matching font"
}

set sample "This is some sample text"
set maxX 120
set maxY 30
set font [findFontForLine {Arial 5 bold} $maxX $maxY $sample]
puts "Chosen font is '$font'"

当我运行代码时,我的系统打印Chosen font is 'Arial 9 bold',但字体和显示可能会略有不同,因此您的里程可能会有所不同.

My system prints Chosen font is 'Arial 9 bold' when I run the code, but fonts and displays can be subtly different so your mileage may well vary.

这篇关于Tk 如何计算小部件大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆