首页 > 解决方案 > 如何在 Python 中从突出显示中计算字符串

问题描述

我希望有一种方法可以通过鼠标突出显示来计算字符串。例如,如果用户突出显示句子中的一个词,它将计算其中有多少个字符串并向用户显示。tkinter 有可能吗?

图片: 在此处输入图像描述

预期输出:它将显示我突出显示的单词中有多少个字符串

标签: pythontkintercount

解决方案


对的,这是可能的。用于text.selection_get()获取文本并将其传递给len.

示例代码:

from tkinter import *


def print_count(event):
    if text.tag_ranges('sel'):
        print(len(text.selection_get()))
        print(len(text.selection_get().split())) # gives count of the number of words highlighted
        #print(text.selection_get())


root = Tk()

text = Text(root)
text.bind('<<Selection>>', print_count)
text.pack()

root.mainloop()


推荐阅读