如何从 Tkinter 文本框中获取选定的字符串? [英] How do I get a selected string in from a Tkinter text box?

查看:47
本文介绍了如何从 Tkinter 文本框中获取选定的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够从文本的突出显示部分中取出一个字符串,我该如何处理?

解决方案

对于 Tkinter.TextTkinter.Entry 小部件,您可以使用:

content = text.selection_get()

从 Python 控制台中的条目和文本小部件获取选定文本的交互式示例:

<预><代码>>>>导入 Tkinter>>>w = Tkinter.Tk()>>>e = Tkinter.Entry(w)>>>e.pack()>>>t = Tkinter.Text(w)>>>t.pack()#(在创建的窗口中的小部件上涂鸦,然后在条目中选择文本)>>>e.selection_get()'1234'#(选择文本)>>>t.selection_get()'1234'>>>

根据 Bryan Oakley 的评论:

<块引用>

selection_get 是适用于所有小部件的通用小部件方法.它并不总是从文本小部件中获取选定的字符串.可能会,但不能保证.它所做的是获得所谓的X"选择(来自 tk 的 X11 根).如果您将 Text 小部件的 exportselection 设置为 False,selection_get 将无法工作.因此,您的建议在正常情况下有效,但并非在所有情况下都有效.

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

解决方案

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.

这篇关于如何从 Tkinter 文本框中获取选定的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆