gpt4 book ai didi

python - Tkinter 索引词问题

转载 作者:太空宇宙 更新时间:2023-11-03 15:06:14 25 4
gpt4 key购买 nike

我正在用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com