Michael Duffett
Michael Duffett

Reputation: 85

Python 3.6 - Updating Tkinter Window During Mainloop

I have been developing a Tkinter application that has a label in it. This label needs to be set to a certain color when a variable equals something, and something else when it equals something else. However, I can't see how to make this logic execute throughout the whole lifespan of the application.

Here is what I have so far:

if variableName.get() == "":
    label4.config(bg = "SystemButtonFace")
else:
    label4.config(bg = "lawngreen")

Thanks in advance!

Upvotes: 0

Views: 421

Answers (2)

Billy7944
Billy7944

Reputation: 1

I built this little function for one of my little python 3.6.4 applications. Hope it helps.

Function to decide if the percentage is positive or negative & colour accordingly.

def range_coin(self,no,pos,coin,vol):
    if eval(str(no)) < 0:
        temp = 'self.' + str(coin)+'l'+str(pos)+'0'+str(vol)+'_la' + '.configure(background = "red")'
        exec(temp)
    else:
        temp = 'self.' + str(coin)+'l'+str(pos)+'0'+str(vol)+'_la' + '.configure(background = "green")'
        exec(temp)
    temp = "self." + str(coin)+"l"+str(pos)+"0"+str(vol)+"_la['text'] =" + str(no)
    exec(temp)

Upvotes: 0

Novel
Novel

Reputation: 13729

You can use the trace method of a tkinter variable to set a function to run whenever the variable is changed.

def update_bg(*args):
    if variableName.get() == "":
        label4.config(bg = "SystemButtonFace")
    else:
        label4.config(bg = "lawngreen")

variableName.trace('w', update_bg)

I don't know your application, but this would seem like the ideal place to make your own Label widget. Here's an example:

import tkinter as tk

class DuffettLabel(tk.Label):
    '''A special type of label that changes the background color when empty'''
    def __init__(self, master=None, **kwargs):
        tk.Label.__init__(self, master, **kwargs)
        self.variable = kwargs.get('textvariable')
        if self.variable is not None:
            self.variable.trace('w', self.update_bg)
            self.update_bg()

    def update_bg(self, *args):
        if self.variable.get() == "":
            self.config(bg = "red")
        else:
            self.config(bg = "lawngreen")

root = tk.Tk()
root.geometry('200x200')
variableName = tk.StringVar()
ent = tk.Entry(root, textvariable=variableName)
ent.pack()
lbl = DuffettLabel(root, textvariable=variableName)
lbl.pack(fill=tk.X)
root.mainloop()

Upvotes: 1

Related Questions