How do I get a selected string in from a Tkinter text box?

前端 未结 3 1394
Happy的楠姐
Happy的楠姐 2020-12-09 11:42

I\'d like to be able to get a string out of a highlighted portion of text, how do I go about this?

3条回答
  •  天涯浪人
    2020-12-09 12:14

    For a Tkinter.Text or Tkinter.Entry widget, you can use:

    content = text.selection_get()
    

    Interactive example of getting selected text both from an Entry and from a Text widgets in the Python console:

    >>> import Tkinter
    >>> w = Tkinter.Tk()
    >>> e = Tkinter.Entry(w)
    >>> e.pack()
    >>> t = Tkinter.Text(w)
    >>> t.pack()
    #(scribble at the widgets in the created window, and select text in the Entry)
    >>> e.selection_get()
    '1234'
    #(select text)
    >>> t.selection_get()
    '1234'
    >>>
    

    According to Bryan Oakley's comment:

    selection_get is a generic widget method available to all widgets. It does not always get the selected string from a Text widget. It might, but it's not guaranteed. What it does is get what's called the "X" selection (from tk's X11 roots). If you set exportselection to False for the Text widget, selection_get will fail to work. So your suggest will work in the normal case, but not in all cases.

提交回复
热议问题