无法从TEXT WIDGET更改背景颜色?

时间:2017-04-12 14:34:53

标签: python text tkinter colors widget

我在一个简单的文本编辑器上练习一个名为" Colorsheme"的简单菜单点,以更改文本小部件的背景颜色(例如像黑暗模式或光模式)。

当我使用自己的脚本时(对我来说它看似合乎逻辑),我没有得到理想的结果。 backgroundcolor不会改变!

这是脚本。你能给我一些提示吗?

# -*- coding: utf-8 -*-

from tkinter import *

col_bg = "white"
col_fg = "grey"

fenster = Tk()
fenster.title("Hello Windowtitle")
fenster.geometry("500x300")
fenster.configure(background="white")


# Definition Text widget
def buildnew_textwidget(col_bg,col_fg):
    T = Text(fenster, height=300, width=200, bg=col_bg, fg=col_fg, bd=0)
    T.pack()
    T.insert(END, "")
buildnew_textwidget(col_bg, col_fg)


# Definition Colors
def Rot():
    col_bg = "red"
    col_fg = "black"
    buildnew_textwidget(col_bg, col_fg)

def Gelb():
    col_bg = "yellow"
    col_fg = "black"
    buildnew_textwidget(col_bg, col_fg)

menu = Menu(fenster)

# Colorsheme
colorsheme = Menu(menu, tearoff=0, background='black',
foreground='#D9CB9E', activebackground='#D9CB9E',
activeforeground='#374140', activeborderwidth=4)

menu.add_cascade(label="Colorsheme", menu=colorsheme)
colorsheme.add_command(label="Rot", command=Rot)
colorsheme.add_command(label="Gelb", command=Gelb)

fenster.config(menu=menu)

mainloop( )

1 个答案:

答案 0 :(得分:1)

您需要稍微更改结构。为了改变颜色使用:T [" bg"] = col_bg和T [" fg"] = col_fg

此外,如果您的T(文本元素)是静态的,最好不要在事件方法

中创建
from tkinter import *

col_bg = "white"
col_fg = "grey"

fenster = Tk()
fenster.title("Hello Windowtitle")
fenster.geometry("500x300")
fenster.configure(background="white")


# Definition Text widget
def buildnew_textwidget(col_bg,col_fg):
    T["bg"] = col_bg
    T["fg"] = col_fg
    T.insert(END, "")

T = Text(fenster, height=300, width=200, bg=col_bg, fg=col_fg, bd=0)
T.pack()

# Definition Colors
def Rot():
    col_bg = "red"
    col_fg = "black"
    buildnew_textwidget(col_bg, col_fg)

def Gelb():
    col_bg = "yellow"
    col_fg = "black"
    buildnew_textwidget(col_bg, col_fg)

menu = Menu(fenster)

# Colorsheme
colorsheme = Menu(menu, tearoff=0, background='black',
foreground='#D9CB9E', activebackground='#D9CB9E',
activeforeground='#374140', activeborderwidth=4)

menu.add_cascade(label="Colorsheme", menu=colorsheme)
colorsheme.add_command(label="Rot", command=Rot)
colorsheme.add_command(label="Gelb", command=Gelb)

fenster.config(menu=menu)

mainloop( )