How to make the text in a Tk label selectable?

与世无争的帅哥 提交于 2019-12-24 08:28:47

问题


I'm creating labels in Tcl Tk, but their text is not selectable (for copy-paste). How do I make is selectable?

I crate the labels using:

set n 0
foreach t $list_of_labels {
    incrr n
    set lbl2 [label .prop_menu.main_frame.val_$n    -text $t]
    grid $lbl2 ...
}

回答1:


You can't without taking a lot of the binding code from some other widget and applying it to your label. If you need this, you would be better taking an entry widget and making it look like a label. Something like:

entry .e1 -textvar t -relief flat -background [$parentWindow cget -background]

If you don't want the focus to move to these then add -takefocus 0.




回答2:


For the text in a label to be selectable en masse, there have to be bindings applied so that the program knows when to select it (as opposed to something else) and there has to be some code to place the code into the selection (or rather the clipboard). The latter is actually pretty simple to do with the clipboard command:

clipboard clear
clipboard append $text

The awkward bit is setting up the bindings and showing that the selection has happened. The simplest is just to do something lame like this (binding to a mouse click):

bind .lbl <1> {
    clipboard clear
    clipboard append [%W cget -text]
    bell
}

OK, that's definitely lame; you can do better! What you won't get is the style of highlighting that Windows's own built in labels often support (where you can drag out a selection and just press Ctrl+C) as that requires the ability to draw the highlight, which Tk's label widgets simply don't have. (You can hack something with entries, but they can't do multiple lines of text, or you could use a text widget but then you have to do a lot of work with bindings to make it behave as you want.)




回答3:


I solved it by using read only entries, I replaced the creation of the label with:

set lbl2 [entry .prop_menu.main_frame.val_$n -relief flat]
$lbl2 insert 0 $t
$lbl2 configure -state readonly

And was able to create entries that act like labels but are selectable.



来源:https://stackoverflow.com/questions/10967056/how-to-make-the-text-in-a-tk-label-selectable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!