繁体   English   中英

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

[英]how I can change the background color and text color of a textbox done with Tkinter?

如何在 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()

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

text.insert(1.0, 'Hello World')

在调用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()

在创建文本框本身时,使用bg确定背景颜色:

text = Text(root, bg = 'black')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM