1

Estoy estudiando POO (Programación orientada a objetos) y tengo esta actividad: "Añade una funcion al boton para cambiar el color de la fuente al label segun el color indicado por el boton" Ya lo he intentado varias veces usando variables como el valor de fg pero no me funciona

from tkinter import *  

class Interface:  
    def __init__(self, contain):  
        self.t = Label(contain, text="Colour",fg="black" bg="white")  
        self.b1 = Button(contain, text="Yellow",fg="black" bg="light grey")  

        self.t.grid(column=0, row=0, columnspan=3)  
        self.b1.grid(column=0, row=1)  


Window = Tk()  
MyInterface = Interface(Window)  
Window.title("TKinter")  
Window.mainloop()  

Como puedo crear correctamente el evento/comando para que esto cambie?

1 respuesta 1

2

Si solo tiene un botón, puede hacer esto:

from tkinter import *  


class Interface:
    def set_label_color_yellow(self):
        self.label['fg'] = "yellow"

    def __init__(self, contain):  
        self.label = Label(contain, text="Colour",fg="black", bg="white")  
        self.button_yellow = Button(contain, text="Yellow", fg="black", bg="light grey", command=self.set_label_color_yellow)

        self.label.grid(column=0, row=0, columnspan=3)  
        self.button_yellow.grid(column=0, row=1)


Window = Tk()  
MyInterface = Interface(Window)  
Window.title("TKinter")  
Window.mainloop()  

Un ejemplo más complejo con varios botones y reproducción de color con lambda:

from tkinter import *  

class Interface:
    def set_label_color(self, color):
        self.label['fg'] = color

    def __init__(self, contain):  
        self.label = Label(contain, text="Colour",fg="black", bg="white")  
        self.button_yellow = Button(contain, text="Yellow", fg="black", bg="light grey", command=lambda: self.set_label_color("yellow"))
        self.button_green = Button(contain, text="Green", fg="black", bg="light grey", command=lambda: self.set_label_color("green"))  

        self.label.grid(column=0, row=0, columnspan=3)  
        self.button_yellow.grid(column=0, row=1)
        self.button_green.grid(column=0, row=2)


Window = Tk()  
MyInterface = Interface(Window)  
Window.title("TKinter")  
Window.mainloop()  

Tu Respuesta

Al pulsar en “Publica tu respuesta”, muestras tu consentimiento a nuestros términos de servicio, política de privacidad y política de cookies

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.