Search code examples
pythonpython-3.xtkinteroperating-systemcopy-paste

How to detect a selected text using python?


I'm looking for a way to copy a selected text in a tkinter.scrolledtext and paste it automatically in an Entry.

Means, Every time a user selects a text it will be added to the tkinter Entry automatically.

Any suggestions? specially on how to get the selected text.


Solution

  • You can use the selection event generated from text widget to add to your entry widget.

    import tkinter as tk
    from tkinter import scrolledtext as tkst
    
    root = tk.Tk()
    
    txt = tkst.ScrolledText(root)
    txt.insert(tk.END, "This is a test phrase")
    txt.pack()
    
    entry = tk.Entry(root)
    entry.pack()
    
    def select_event(event):
        try:
            entry.delete(0, tk.END)
            entry.insert(0, txt.get(tk.SEL_FIRST, tk.SEL_LAST))
        except tk.TclError:
            pass
    
    txt.bind("<<Selection>>", select_event)
    
    root.mainloop()