同时在多个文本小部件中进行多项选择

Multiple selections at multiple Text widgets at the same time

我有这个示例应用程序。

#!/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 个文本小部件,但我不能 select 它们中的文本,当我 select text1 中的文本然后尝试 select text2 中的文本然后 selection 来自 text1 消失。看起来 tkinter 只允许一个文本 selection 每个应用程序而不是每个小部件。

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

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

Tkinter 起源于 X 窗口系统。 X有一个概念叫做"selection",类似于系统剪贴板(更准确的说,剪贴板就是"PRIMARY"选区)。默认情况下,一些 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.