Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
249 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...