在 guizero Python 3 中单击按钮时如何更改颜色?

How to change colour when I click a button in guizero Python 3?

所以我在 python3 guizero 中编写了这段代码,当我点击我创建的按钮时将颜色更改为红色。但无论我做什么都行不通!我不确定我做错了什么但它不起作用(我使用 Visual Studio 代码但它没有给我任何错误或说代码错误。)所以我认为这将是最好的地方来。 这是我写的代码:

from guizero import *

red = 255,0,0

def cl_ch():
    if mahe_pushbutton.text == "Push":
        mahe_text.text_colour = red
    else:
        print("Not working")

mahe_app = App(title = "TEST")

mahe_text = Text(mahe_app, text = "test test", font = "Orbitron", size = 20)

mahe_textbox = TextBox(mahe_app, width = 50)



mahe_pushbutton = PushButton(mahe_app, command=cl_ch, text = "Push")

mahe_pushbutton.width = 60

mahe_pushbutton.height = 3



mahe_app.display()

如果您能提供帮助,谢谢!

您好,我才刚刚开始关注 Guizero,我的编程技能不是很先进,但是 这应该使文本在您按下按钮时变为红色,但之后仍保持红色。

from guizero import *

red = 255,0,0

def cl_ch():        

    mahe_text.text_color = "red"


mahe_app = App(title = "TEST")

mahe_text = Text(mahe_app, text = "test test", font = "Orbitron", size = 20)

mahe_textbox = TextBox(mahe_app, width = 50)

mahe_pushbutton = PushButton(mahe_app, command=cl_ch, text = "Push")

mahe_pushbutton.width = 60

mahe_pushbutton.height = 3

mahe_app.display()

下一位在大约一秒或 1000 毫秒后粗略地将文本重置为黑色

from guizero import *

red = 255,0,0

def cl_ch():        

    mahe_text.text_color = "red"
    
def cl_ch_2():

    mahe_text.text_color = "black"

mahe_app = App(title = "TEST")

mahe_text = Text(mahe_app, text = "test test", font = "Orbitron", size = 20)

mahe_textbox = TextBox(mahe_app, width = 50)

mahe_text.repeat(1000,cl_ch_2) # a kind of counter that reset the colour back to black

mahe_pushbutton = PushButton(mahe_app, command=cl_ch, text = "Push")

mahe_pushbutton.width = 60

mahe_pushbutton.height = 3

mahe_app.display()

当您按下按钮时,它会运行 cl_ch 函数,因此您只需要更新文本的一个属性或方法,即 text_color.

虽然我不知道如何将其重置,所以我只是在 1000 毫秒后编码了一个重复文本作为重置。

希望有所帮助

from guizero import *

red = (255,0,0)



mahe_app = App(title = "TEST")

mahe_text = Text(mahe_app, text = "test test", font = "Orbitron", size = 20)


def cl_ch():
    mahe_text.text_color = red

def refresh():
    mahe_text.text_color = "black"



mahe_textbox = TextBox(mahe_app, width = 50)



mahe_pushbutton = PushButton(mahe_app, command=cl_ch, text = "Push")

mahe_pushbutton.width = 60

mahe_pushbutton.height = 3


mahe_app.repeat(250, refresh)
mahe_app.display()

你需要 red = (255,0,0) 而不是 red = 255,0,0 该函数必须在文本之后声明或接收文本作为入口参数。 如果您从不更改按钮中的文本,请删除条件,因为它将始终在 if 中输入,而永远不会在 else 中输入。 我不知道您是否希望文本再次变黑,所以我创建了一个将文本变黑的函数,并使用应用程序中的重复方法每 250 毫秒将文本变黑