索引词问题

2024-04-23 14:26:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用python2.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()

如何配置此选项,以便打印用户可以打印整个连字符,而不必在连字符处拆分?例如,根据您单击的位置打印字符串“dash between”而不是“dash”、“between”或“-”。在


Tags: textmastereventconfigreturnbindtkinterdef
1条回答
网友
1楼 · 发布于 2024-04-23 14:26:11

您不能修改"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.

您可以使用文本小部件的内置搜索功能来查找单词的开头和结尾,无论您想如何定义“word”。您可以搜索正则表达式,因此可以搜索类似[-\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,您的代码将更容易理解和维护,除非绝对必要,而且在这种情况下绝对没有必要。使用上述代码,您可以将绑定简化为:

^{pr2}$

相关问题 更多 >