如何更改使用 Tkinter 完成的文本框的背景颜色和文本颜色?

Ful*_*nza 2 python tkinter background-color

如何在 python 中更改使用 Tkinter 完成的文本框的背景颜色?我使用了下面的代码,但我不明白为什么它不起作用

from Tkinter import *

def onclick():
   pass

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

text.tag_add("here", "1.0", "1.4")
text.tag_add("start", "1.8", "1.13")
text.tag_config("here", background="black", foreground="green")
root.mainloop()
Run Code Online (Sandbox Code Playgroud)

atl*_*ist 5

它确实有效。如果插入文本:

text.insert(1.0, 'Hello World')
Run Code Online (Sandbox Code Playgroud)

在调用tag_addtag_config方法之前,该标签将附加到插入的文本。但是,在当前调用它时,没有可插入标签的索引,因此实际上没有标签。

如果要在用户在小部件中键入时实时修改文本内容,可以将文本小部件绑定到按键事件,该事件调用为文本小部件添加和配置标签的函数:

from Tkinter import *

def track_change_to_text(event):
    text.tag_add("here", "1.0", "1.4")
    text.tag_config("here", background="black", foreground="green")

root = Tk()

text = Text(root)
text.pack()

text.bind('<KeyPress>', track_change_to_text)

root.mainloop()
Run Code Online (Sandbox Code Playgroud)