BPS
BPS

Reputation: 1231

Multiple selections at multiple Text widgets at the same time

I have this sample app.

#!/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()

I have 2 text widgets but I cant select text in both of them, when I select text in text1 and then try to select text in text2 then selection from text1 disappears. It looks like tkinter allows only one text selection per application and not per widget.

Is there any mechanism in tkinter which will allow me to select text in both text widgets at the same time or I must implement this by my own?

Upvotes: 2

Views: 392

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 386220

Short answer: set the exportselection attribute of each Text widget to False

Tkinter has its roots in the X windowing system. X has a concept called a "selection", which is similar to the system clipboard (more accurately, the clipboard is the "PRIMARY" selection). By default, several of the tkinter widgets export their selection to be the PRIMARY selection. An application can only have one PRIMARY selection at a time, which is why the highlight disappears when you click between two Text widgets.

Tkinter gives you control over this behavior with the exportselection configuration option for the Text widget as well as the Entry and Listbox widgets. Setting it to False prevents the export of the selection to the X selection, allowing the widget to retain its selection when a different widget gets focus.

For example:

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

Quoting from the 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.

Upvotes: 3

Related Questions