如何使条目中的部分文本加粗并更改其背景色?

2024-04-26 06:55:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创建一个基于Tkinter的GUI,它有一个入口小部件。我想使它的文本加粗的一部分,并改变其背景颜色。但我不知道我该怎么做。如果我使用文本小部件,我可以只使用标记,但看起来它们不能与条目小部件一起使用:

此代码正在使用文本小部件:

import tkinter as tk
from tkinter.font import Font


root = tk.Tk()
text = tk.Text(root, font=Font(size=12))
text.insert("1.0", "I want THIS PART to be bold and have red background")
text.tag_configure("bold-and-red", font=Font(size=12, weight="bold"), background="red")
text.tag_add("bold-and-red", "1.7", "1.16")
text.pack()
root.mainloop()

一切正常(显示文本小部件,“此部分”为粗体,背景为红色)

此代码正在使用Entry小部件:

import tkinter as tk
from tkinter.font import Font


root = tk.Tk()
entry = tk.Entry(root, font=Font(size=12))
entry.insert(0, "I want THIS PART to be bold and have red background")
entry.tag_configure("bold-and-red", font=Font(size=12, weight="bold"), background="red")
entry.tag_add("bold-and-red", 7, 16)
entry.pack()
root.mainloop()

我刚刚得到一个错误:

AttributeError: 'Entry' object has no attribute 'tag_configure'

有没有一种方法可以实现我对Entry widget的要求


Tags: andtext文本importsize部件tkintertag
2条回答

正如@BryanOakley所说,只改变某些字符外观的唯一方法是使用一个定制的Text小部件

下面是一个示例实现:

import tkinter as tk
from tkinter.font import Font


class OneLineText(tk.Text):
    def __init__(self, master, *args, **kwargs):     
        super().__init__(master, *args, height=1, wrap="none", **kwargs)

        self.bind("<Return>", lambda event: "break")
        self.bind("<Key>", self.on_keypress)
        self.bind("<Control-a>", self.select_all)
        self.bind("<Control-A>", self.select_all)
        self.bind("<Control-v>", lambda event: self.see("end"))
        self.bind("<Control-V>", lambda event: self.see("end"))

    def on_keypress(self, event):
        self.see("end-1c")

    def select_all(self, event):
        self.tag_add("sel", "1.0", "end-1c")
        return "break"

    def insert(self, index, string):
        string = string.replace("\n", "")
        if isinstance(index, int):
            super().insert("1.{}".format(index), string)
            return
        if index == "end":
            super().insert("end-1c", string)
            return
        super().insert(index, string)

    def get(self):
        return super().get("1.0", "end-1c")

root = tk.Tk()
entry = OneLineText(root, font=Font(size=12))
entry.insert(0, "I want THIS PART to be bold and have red background")
entry.tag_configure("bold-and-red", font=Font(size=12, weight="bold"), background="red")
entry.tag_add("bold-and-red", "1.7", "1.16")
entry.pack()
root.mainloop()

文本小部件的insertget方法被修改为与条目小部件中的方法一样工作

A screenshot

How can I make part of the text in the Entry bold and change its background color? ... If I use the Text widget I can just use tags but it looks like they can't be used with Entry widget:

你是对的:除了通过选择机制之外,你不能只改变条目小部件中某些字符的外观

如果只想更改某些字符的外观,则需要使用单行Text小部件

相关问题 更多 >