Skip to content
Advertisement

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

So I have written this piece of code in python3 guizero to change colour to red when I click the button I created. But whatever I do it’s not working! I am not sure what I did wrong but it just won’t work (I used Visual Studio Code but it didn’t give me any errors or say the code was wrong.) So I figured this will be the best place to come. This is the code I wrote:

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

Thanks if you are able to help!

Advertisement

Answer

Hi I’ve only just started looking at Guizero, my programming skills aren’t very advanced but This should make the text red when you press the button but stays red afterwards.

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

This next bit crudely resets the text to black after about a second or 1000 miliseconds

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

When you push the button it runs the cl_ch function so you just need to update that one attribute or method of the Text which is the text_color.

I can’t figure out how to set it back though so I just coded a repeat text after 1000 miliseconds as a reset.

hope that helped

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement