如何使 tkinter 文本小部件无法选择? [英] How can I make a tkinter text widget unselectable?

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

问题描述

我想让我的 tkinter Text 只是一个输出而不是一个输入.通过一些研究,我发现 text.config(state="disabled") 禁用了用户输入,但它仍然允许选择我不想要的文本.

I want to make my tkinter Text to be only an output and not an input. Through some research I've found that text.config(state="disabled") disables user input, but it still allows for selecting text, which I do not want.

如何让我的 Text 小部件不可选择和不可写?

How can I get my Text widget to be unselectable and unwritable?

推荐答案

最简单的方法是替换支持选择的默认文本绑定,使它们什么都不做.有几种方法可以做到这一点:使用绑定标签,您可以删除所有默认绑定,或者您可以仅删除默认绑定子集的绑定.

The simplest way is to replace the default text bindings that support selection so that they do nothing. There are a couple ways to do this: using binding tags you can remove all default bindings, or you can remove the bindings to only a subset of default bindings.

小部件上的所有绑定——包括默认绑定——都与绑定标签(也称为bindtags")相关联.文本小部件的绑定标签是Text",文本小部件的所有默认绑定都与此标签相关联.如果删除该绑定标记,则会删除所有文本特定的绑定.

All bindings on widgets -- including the default bindings -- are associated with binding tags (also called "bindtags"). The binding tag for the the text widget is "Text", and all default bindings for the text widget are associated with this tag. If you remove that binding tag, you remove all Text-specific bindings.

任何小部件的默认绑定标签是小部件的字符串表示、内部小部件类(在本例中为Text")、顶层窗口的内部名称(在本例中为根)的元组,和特殊标签全部".

The default binding tags for any widget is a tuple of the string representation of the widget, the internal widget class (in this case, "Text"), the internal name of the toplevel window (in this case, root), and the special tag "all".

在下面的示例中,我们更改了绑定标签,以便不包含文本",从而有效地删除了文本小部件上的所有默认绑定:

In the following example we change the binding tags so that "Text" is not included, effectively removing all default bindings on the text widget:

import tkinter as tk

root = tk.Tk()
text = tk.Text(root)
text.bindtags((str(text), str(root), "all"))

删除特定绑定

如果您希望保留一些默认绑定,您可以只替换您不想要的那些.您可以通过创建自己的绑定来实现这一点,并让这些绑定返回字符串break".这个特殊的返回值告诉 tkinter 停止进一步处理事件.

Removing specific bindings

If you prefer to keep some of the default bindings, you can replace just the ones that you don't want. You do that by creating your own bindings, and having those bindings return the string "break". This special return value tells tkinter to stop processing the event any further.

例如,要防止双击选择光标下的单词,您可以这样做:

For example, to prevent a double-click from selecting the word under the cursor you could do this:

text.bind("<Double-1>", lambda event: "break")

这种方法的缺点是您必须弄清楚与选择机制相关的所有绑定是什么.另一方面,它使您可以完全控制每个按键或按钮的作用.

The downside to this approach is that you have to figure out what all of the bindings are that are related to the selection mechanism. On the other hand, it gives you complete control over what each key or button press does.

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

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