【问题标题】:Is there an efficient way to tell if text is selected in a Tkinter Text widget?有没有一种有效的方法来判断是否在 Tkinter Text 小部件中选择了文本?
【发布时间】:2011-05-22 21:41:36
【问题描述】:

this page describing the Tkinter text widget,据说 '选择是一个名为SEL(或“sel”)的特殊标签,对应于当前选择。您可以使用常量 SEL_FIRST 和 SEL_LAST 来引用选择。如果没有选择,Tkinter 会引发 TclError 异常。'

我的问题:有没有更有效的方法来判断 Text 小部件中是否有选择,除了愚弄异常,如下面的代码?

seltext = None
try:
   seltext = txt.get(SEL_FIRST, SEL_LAST)
except TclError:
   pass

if seltext:
   # do something with text

【问题讨论】:

    标签: python text tkinter selection


    【解决方案1】:

    您可以向小部件询问“sel”标签包含的文本范围。如果没有选择,则范围的长度为零:

    if txt.tag_ranges("sel"):
        print "there is a selection"
    else:
        print "there is no selection"
    

    【讨论】:

    • 需要注意的是tag_ranges会返回一个包含标签名的文本范围列表。因此,如果您需要它们,这可能会很有用(就像我在这个特定时刻所做的那样,因此我发表了评论)。
    【解决方案2】:

    这是一种检查是否选择了指定位置的方法。

    if "sel" in myTextWidget.tag_names(INSERT): #use 'not in' to see if it's not selected
        print("INSERT to 'insert+1c' is selected text!");
    

    我不知道他们为什么不让你在里面放第二个索引。我也不知道这对处理器来说比你的版本更有效,但据我所知,它似乎更标准。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-06
      • 2011-06-17
      • 2012-11-27
      • 2012-12-28
      • 1970-01-01
      • 1970-01-01
      • 2011-09-16
      相关资源
      最近更新 更多