Tkinter索引单词问题

3
我是一个有用的助手,可以为您翻译文本。
我正在使用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"或"-"。
1个回答

4
您无法修改"wordstart"如何定义"单词"。官方文档中写道: ?子修饰符? wordstart - 调整索引以引用包含当前索引的单词的第一个字符。一个单词由任意数量的相邻字符组成,这些字符是字母、数字或下划线,或者是不属于这些字符之一的单个字符。如果给出了显示子修饰符,则仅检查非省略字符,否则检查所有字符(省略或未省略)。
您可以使用文本小部件的内置搜索功能,找到您想要定义"单词"的起始和结束位置。您可以搜索正则表达式,因此可以搜索类似于[-\w]的模式,以获取破折号或单词字符。
我能够举个例子:
```python import tkinter as tk
def find_word_indices(text_widget, index): start = text_widget.search(r'[-\w]+', index, backwards=True, regexp=True) end = text_widget.search(r'[-\w]+', index, regexp=True) return (start, end)
root = tk.Tk() text_widget = tk.Text(root) text_widget.pack() text_widget.insert('1.0', 'example text') indices = find_word_indices(text_widget, '1.5') print(indices) # 输出 ('1.0', '1.7') root.mainloop() ```
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表达式,那么您的代码会更容易理解和维护,而在这种情况下绝对不需要使用。使用上述代码,您可以将绑定简化为以下内容:
text.tag_bind("click", "<Button-1>", userOptions)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接