簡體   English   中英

如何獲得多行textwidget中子字符串的結束位置

[英]How do I get a the end position of substring in a multiline textwidget

我有一個文本控件,里面有文本,它有'\\n'字符。 文本由行分隔。 我嘗試使用搜索方法在文本小部件中找到子字符串的開始位置。 然后我有一個(2,10)的職位。 之后,我計算了子字符串的長度(18),並通過將長度添加到開始位置來找出結束位置,得到了類似2.28的值。 但是,當子字符串中有一個'\\n'符號時,它將是錯誤的位置。 例如,如果'\\n'符號位於2.15位置,則小部件中子字符串的結尾應為3.13。 有沒有辦法在多行文本小部件中找到結束位置? 我可以使用搜索方法嗎? 我怎樣才能做到這一點?

這是您可能要計算每一行的一種方法。 此方法將逐行計數每一行,總計數減去\\n

下面的功能將檢查每行並計數。 打印該行的結果,然后將這些結果添加到計數器中。 最后,完成循環后,它將打印總計數。 我還添加了一條打印語句,該語句將為文本框中的每一行提供最后一個字符的索引。

import tkinter as tk


root = tk.Tk()
root.geometry("250x100")
txt = tk.Text(root, height=4, width=30)
txt.pack()


def string_count():
    global txt
    counter = 0
    for ndex, line in enumerate(txt.get(1.0, "end-1c").splitlines()):
        counter += len(line)
        print("Count on Line {} is: {}".format(ndex + 1, len(line)))
        print("The index for the last character in this line is {}.{}".format(ndex + 1, len(line)))
    print("String count in text box is: {}".format(counter))

tk.Button(root, text="Get string count", command=string_count).pack()
root.mainloop()

結果:

在此處輸入圖片說明

如果您有一個索引要查找距離N個字符的新索引,則可以使用index方法以及文本小部件的擴展語法(例如:“ line.character + n chars”)

這是一個工作示例:

import tkinter as tk

root = tk.Tk()
text = tk.Text(root)

text.insert("end", "line one\nthis is line two\nand this is the third line")

index = "2.10"
new_index = text.index("{} + {} chars".format(index, 18))
assert(new_index=="3.11")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM