简体   繁体   English

根据另一个变量的大小在tkinter中显示有色变量

[英]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. 我正在使用Tkinter根据剩余库存量以不同的颜色显示漫画书。 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. 颜色的图像起作用,但文本不起作用因此,文本和颜色在外壳中起作用,但是只有颜色在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 . 我相信您的问题是,您正在为每个 Label重复使用相同的 StringVar You should be allocating a StringVar for each Label . 您应该为每个 Label分配一个StringVar 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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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