Tkinter:在文本框中显示/隐藏特定文本

时间:2018-11-02 17:42:18

标签: python python-3.x tkinter

说明:

我有一个文本框。请参见下图。

enter image description here


问题:

我希望在单击“隐藏”按钮时隐藏突出显示的文本。然后,当我单击“显示”按钮(图片中没有)时显示文本。 与pack()和pack_forget()类似,但是这次是针对文本而不是窗口小部件。

1 个答案:

答案 0 :(得分:2)

您可以将标签添加到文本区域,并使用elide=True配置标签以隐藏文本,并将其设置为elide=False以显示文本。

这是一个小例子:

import tkinter as tk

def hide():
    text.tag_add("hidden", "sel.first", "sel.last")

def show_all():
    text.tag_remove("hidden", "1.0", "end")

root = tk.Tk()
toolbar = tk.Frame(root)
hide_button = tk.Button(toolbar, text="Hide selected text", command=hide)
show_button = tk.Button(toolbar, text="Show all", command=show_all)
hide_button.pack(side="left")
show_button.pack(side="left")

text = tk.Text(root)
text.tag_configure("hidden", elide=True, background="red")

with open(__file__, "r") as f:
    text.insert("end", f.read())

toolbar.pack(side="top", fill="x")
text.pack(side="top", fill="both", expand=True)

text.tag_add("sel", "3.0", "8.0")
root.mainloop()
相关问题