python - 同时在多个文本小部件上进行多项选择

标签 python tkinter tk-toolkit

我有这个示例应用程序。

#!/usr/bin/env python3

from tkinter import *


class App(Tk):
    def __init__(self):
        super().__init__()
        text1 = Text(self)
        text1.insert('1.0', 'some text...')
        text1.pack()
        text2 = Text(self)
        text2.insert('1.0', 'some text...')
        text2.pack()

App().mainloop()

我有 2 个文本小部件,但我无法在这两个小部件中选择文本,当我在 text1 中选择文本,然后尝试在 text2 中选择文本时,text1 中的选择就会消失。看起来 tkinter 只允许每个应用程序而不是每个小部件选择一个文本。

tkinter 中是否有任何机制允许我同时选择两个文本小部件中的文本,或者我必须自己实现?

最佳答案

简短回答:将每个文本小部件的 exportselection 属性设置为 False

Tkinter 起源于 X 窗口系统。 X有一个称为“选择”的概念,它类似于系统剪贴板(更准确地说,剪贴板是“主要”选择)。默认情况下,一些 tkinter 小部件将其选择导出为主要选择。一个应用程序一次只能有一个主要选择,这就是当您在两个文本小部件之间单击时突出显示会消失的原因。

Tkinter 使您可以通过文本小部件以及条目和列表框小部件的 exportselection 配置选项来控制此行为。将其设置为 False 可以防止将选择导出到 X 选择,从而允许小部件在不同的小部件获得焦点时保留其选择。

例如:

import tkinter as tk
...
text1 = tk.Text(..., exportselection=False)
text2 = tk.Text(..., exportselection=False)

引自official tk documentation :

exportselection Specifies whether or not a selection in the widget should also be the X selection. The value may have any of the forms accepted by Tcl_GetBoolean, such as true, false, 0, 1, yes, or no. If the selection is exported, then selecting in the widget deselects the current X selection, selecting outside the widget deselects any widget selection, and the widget will respond to selection retrieval requests when it has a selection. The default is usually for widgets to export selections.

关于python - 同时在多个文本小部件上进行多项选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42022785/

相关文章:

python - 旋转箱输出值

python - 如何通过单击按钮重新启动 tkinter/python 程序?

ruby - Ruby 是否提供响应 OS X 上的 Apple 事件的机制?

python - 如何在python中查找列表中的最大位数

python - `python -m pip install` 是做什么的?

python - 为什么我的文字不向左显示?

python - 全局变量不会改变

bind - 如何绑定(bind) '+'和 '-'键是Tcl/Tk

python - 如何找到列表S的所有分区为k个子集(可以为空)?

python Pandas : replace values based on location not index value