首页 > 解决方案 > 通过变量列表更改颜色和文本时,Tkinter 标签小部件的奇怪行为

问题描述

我正在构建一个小会计工具,所以我不再把钱花在无用的东西上。

由于我正在处理大量发票列表,因此我想按类别对它们进行结构化和着色,因为我需要知道一般在哪里削减支出。

由于列表框不支持多行文本并且没有颜色,我想使用滚动时动态变化的按钮。

我发现按钮不支持字体,这使得使用长 IBAN 字符串非常糟糕。

然后我决定使用提供着色、字体和多行的标签小部件,并创建了我自己的小部件。

这是当用户滚动并且标签必须更改颜色和文本时调用的函数:

def Refresh (self):

    for button in self.buttons:
        
        try:

            index = self.buttons.index(button) + self.ListIndex


            if type(self.textList[index]) is list:

    
                button.configure(text = self.textList[index][0] , bg = self.textList[index][1])
                

            else:

                button.config(text = self.textList[index])

        except IndexError:
                button.config(text = " ",bg = "#d9d9d9")

可变样本:

self.buttons = A list of Label references created when the Widget gets called length depends on how many buttons the user wants being displayed

self.ListIndex = Basically an Index offset, which gets in/decremented when the user is scrolling up or down

self.textList = list of config data for the Labels which elements maybe string or list
self.textList = [['foo', '#eb3434'],'bar']

index = 0
self.textList[index][0] = Invoice Details to be displayed
self.textList[index][1] = Invoice Group Color for easy recognition

现在只有文本配置:

button.configure(text = self.textList[index][0])

预期结果:

在此处输入图像描述

现在,当我尝试使用以下方式配置颜色时,这很奇怪:

button.configure(text = self.textList[index][0] , bg = self.textList[index][1])

非预期结果:

在此处输入图像描述

滚动后:

在此处输入图像描述

经过一点语义调试后,我发现颜色的位置正确。文字和颜色出现的地方是随机的。

标签: pythontkinter

解决方案


推荐阅读