首页 > 解决方案 > Tkinter:在文本框中显示/隐藏特定文本

问题描述

描述:

我有一个带有文本的文本框。见下图。

在此处输入图像描述


问题:

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

标签: pythonpython-3.xtkinter

解决方案


您可以将标签添加到文本区域,并将标签配置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()

推荐阅读