gpt4 book ai didi

python - 无法从文本小部件更改背景颜色?

转载 作者:太空宇宙 更新时间:2023-11-03 15:23:05 25 4
gpt4 key购买 nike

我在一个简单的文本编辑器上进行练习,其中有一个名为“Colorsheme”的简单菜单点,以更改文本小部件的背景颜色(例如深色模式或浅色模式)。

当我使用自己的脚本时(对我来说它看起来很合乎逻辑),我没有得到想要的结果。背景颜色没有改变!

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

# -*- 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( )

最佳答案

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

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

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( )

关于python - 无法从文本小部件更改背景颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43372610/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com