python - Tkinter 索引词问题

标签 python regex python-2.7 indexing tkinter

我正在用 python 2.7 编写 Tkinter 应用程序。我正在使用 wordstart 和 wordend 索引来获取被点击的单词。这对常规单词非常有效,但不适用于带连字符的单词。

这是我的代码:

from Tkinter import *

master = Tk()

def userOptions(event, clickposition):
    index1 = clickposition + " wordstart"
    index2 = clickposition + " wordend"
    user = text.get(index1, index2)
    print user
    return

def userEnter(event):
    text.config(cursor="hand2")
    return

def userLeave(event):
    text.config(cursor="arrow")
    return  

text = Text(master)
text.insert(INSERT, "This is a sentence\n")
text.insert(INSERT, "This is a sentence with dashes-between some-words\n")
text.pack()
text.tag_add("click", "1.0", "end")
text.tag_bind("click", "<Enter>", userEnter)
text.tag_bind("click", "<Leave>", userLeave)
text.tag_bind("click", "<Button-1>", lambda event: userOptions(event, text.index("@%d,%d" % (event.x, event.y))))
text.config(state = DISABLED)

master.mainloop()

我如何配置它以便打印用户可以打印整个带连字符的单词而不在连字符处拆分?例如,根据您点击的位置打印字符串“dashes-between”而不是“dashes”、“between”或“-”。

最佳答案

您不能修改 "wordstart" 定义“单词”的方式。来自官方文档:

?submodifier? wordstart - Adjust the index to refer to the first character of the word containing the current index. A word consists of any number of adjacent characters that are letters, digits, or underscores, or a single character that is not one of these. If the display submodifier is given, this only examines non-elided characters, otherwise all characters (elided or not) are examined.

您可以使用文本小部件的内置搜索功能来查找您想要定义“单词”的单词的开头和结尾。您可以搜索正则表达式,这样您就可以搜索类似 [-\w] 的模式来获取破折号或单词字符。

在我的脑海中,它可能看起来像这样:

def userOptions(event):
    count = IntVar()
    pattern = r'[-\w]+'

    # find the beginning of the "word", starting _after_
    # the character clicked on
    start = "@%d,%d +1c" % (event.x, event.y)
    index1 = text.search(pattern, start, backwards=True, regexp=True)

    # starting with the beginning, find the end and save
    # the number of characters that matched.
    text.search(pattern, index1, regexp=True, count=count)

    # compute the ending index of the match
    index2=text.index("%s + %s c" % (index1, count.get()))

    # get the text
    user = text.get(index1, index2)
    print user
    return

顺便说一句,如果你避免使用 lambda,除非绝对必要,否则你的代码将更容易理解和维护,在这种情况下绝对没有必要。使用上面的代码,您可以简化对此的绑定(bind):

text.tag_bind("click", "<Button-1>", userOptions)

关于python - Tkinter 索引词问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32320066/

相关文章:

regex - Perl 正则表达式删除除最后一次出现之外的所有内容

regex - 替换正则表达式中的换行符

javascript - 如何通过 jQuery 选择文本并使用正则表达式替换它?

python - 使用 Python 2.7 函数返回的值在同一行打印

Python abc.abstractproperty 兼容性

python - 如何将外部 jar 库导入 Hortonworks 中的 ZEPPELIN?

python - NoReverseMatch for get_absolute_url() 新手问题

python - Paraview:从积分变量中获取点数据

python - 通过向下而不是横向获取数据帧值?

python - Peewee 抛出 KeyError : 'f'