2

I'm trying to display binary information in a widget (ie. text, entry, label). The individual characters, in this case only '0' or '1' should be clickable so that they toggle between 0 and 1.

I'm not quite sure which widget to use and how to bind a mouse event to a individual character.

I hope someone can point me into the right direction, since I'm fairly new to the TK side of things.

4

1 回答 1

5

最简单的两个小部件是canvastext。使用画布,您可以将数字字符串设置为单个文本项,然后自己将点击位置转换为字符索引,或者(更有可能)使每个字符成为其自己的文本项。(就像您可以以最小的努力使每个角色都可以单独设置样式和可点击,但是您需要注意事物的布局方面。)

但是,我认为文本小部件可能更合适。这使您可以在字符范围上设置标签,并且这些标签既可绑定又可设置样式。

pack [text .t -takefocus 0]
set binstring "01011010"
set counter 0
foreach char [split $binstring ""] {
    set tag ch$counter
    .t insert end $char $tag
    .t tag bind $tag <Enter> ".t tag configure $tag -foreground red"
    .t tag bind $tag <Leave> ".t tag configure $tag -foreground black"
    .t tag bind $tag <1> [list clicked .t $tag $counter]
    incr counter
}
proc clicked {w tag counter} {
    global binstring
    # Update the display
    set idx [$w index $tag.first]
    set ch [expr {![$w get $idx]}]
    $w delete $idx
    $w insert $idx $ch $tag
    # Update the variable
    set binstring [string replace $binstring $counter $counter $ch]
    # Print the current state
    puts "binstring is now $binstring"
}
于 2013-06-14T08:14:12.247 回答