How to change the color of the text outside of a Tkinter function?

Asked

Viewed 20 times

-1

I’m trying to change the color of a text outside of a function with Tkinter. I tried to put the label inside the function but keeps overwriting one text on the other. Follows the code.

from tkinter import *
from tkinter import ttk
import tkinter as tk

var_35='black'
fg1='black'

master = Tk()
master.geometry('850x700')
master.title('Vias Size')


w = Canvas(master, width=600, height=400, bg='white')
w.grid(row=20,column=0, columnspan=10)



def Solve():
    global fg1
    wth = int(cth.get())
    fg1='black'
    ring = "Ring size = %d µm" % (wth)
    if wth>120:
        fg1 = 'orange'
        print (fg1)
        var12.set(ring)
    elif wth>80:
        fg1= 'red'
        print (fg1)
        var12.set(ring)
    else:
        print (fg1)
        var12.set(ring)


var_1=StringVar()
Label_10 = Label(master, textvariable = var_1,font=('Arial',15),padx=5).grid(row=1,column=0, columnspan=5)

var12=StringVar()
print(fg1)
Label_12 = tk.Label(master, textvariable=var12, font=('Arial',12),padx=5, fg=fg1, bg='white').place(x=80, y=440)


Button(master, text='Solve',font=('Arial',14), command=Solve).grid(row=10,column=7, columnspan=1)

cth = ttk.Combobox(master, values=('25','35', '50','100', '150', '200'),font=('Arial',12) ,width=8)
cth.current(0)
cth.grid(row=6,column=3, columnspan=1)

mainloop()

1 answer

-1


Hello, all right?

Well first we have to solve a problem in the code above... You assigned the variable Label_12 the instance of a Label already with the place, this makes it impossible to work with the properties of the Label, so first you instantiate the Label and then perform the place

    Label_12 = tk.Label(master, textvariable=var12, font=('Arial',12),padx=5, fg=fg1, bg='white')
    Label_12.place(x=80, y=440)

Now within the function apply the following command:

    **Label_12['foreground'] = fg1**

So you change the color according to the function parameter....

your code would look like this:

#########################################################

inserir a descrição da imagem aqui

#########################################################

Another tip, avoid using global variable, this can cause you some problems for you, apply the variable as a function parameter, would be better

I hope I’ve helped.

  • Hi, thanks for the answer, I was already thinking that this was not possible. So, I left the fg1 as global to test if it would take the value of the color to the label but had not solved, I will leave the variable within the function. Thanks again. abs

  • Whoop, imagine & #Xa;;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.