简体   繁体   中英

Displaying colored variables in tkinter based on size of another variable

I am using Tkinter to display comic books in different colours based on the amount of stock remaining. The colour part of the function is working correctly and the object/ class is working fine but it is only displaying the text of the last object in the list as shown in the image and shell.

Function.

stock = StringVar()
def update_label():
    counter = 1
    for c in comics:
        stock.set("")
        counter += 1
        if c._stock >= 10:
            colour = "green"
        elif c._stock <= 3:
            colour = "red"
        elif c._stock <= 6:
            colour = "orange"
        stock.set(c._name + " - " + str(c._stock)+ " remaining")
        print (colour)
        print (stock.get())
        Label(stock_frame, textvariable=stock, fg = colour, bg ="#333333").grid(row=counter, column = 0, pady=(0,10))

Shell output.

orange
A Great Comic - 7 remaining
red
Jerry Java - 1 remaining
green
Tony Tkinter - 11 remaining
orange
Scratch The Cat - 5 remaining
red
Python Panic - 3 remaining
>>> 

Image of colours working but not text So the text and colours are working in the shell but only the colours are working in the GUI. I am assuming the problem is with the label and the text variable but I cannot figure out why it is only repeating the last object in the list.

Thanks in advance

I believe your problem is that you are reusing the same StringVar for every Label . You should be allocating a StringVar for each Label . You didn't provide enough code for me to test this, but I believe it would go something like:

stocks = [StringVar() for comic in comics]

def update_label():

    for counter, comic in enumerate(comics):
        stock = stocks[counter]
        stock.set("")

        if comic._stock >= 10:
            colour = "green"
        elif comic._stock <= 3:
            colour = "red"
        elif comic._stock <= 6:
            colour = "orange"

        stock.set(comic._name + " - " + str(comic._stock) + " remaining")
        print(colour)
        print(stock.get())
        Label(stock_frame, textvariable=stock, fg=colour, bg="#333333").grid(row=counter + 2, column=0, pady=(0, 10))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM