鱼C论坛

 找回密码
 立即注册
查看: 1472|回复: 2

[已解决]Tkinter 定时刷新颜色

[复制链接]
发表于 2023-8-18 14:55:38 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
from tkinter import  *
import time
root=Tk()
root.title("定时刷新颜色")
abc=["red","green","blue","indigo","yellow"]
def refresh():
      for i in abc :
            l=Label(root,text="COLOR",foreground=abc)
            root.after(1000,refresh)
            l.pack()
root.after(1000, refresh)
mainloop()

错  误  在  哪  里  ?
最佳答案
2023-8-18 14:56:05
错误在于在刷新函数中,创建了多个Label,并且没有正确设置Label的前景色属性。下面是修正后的代码:
from tkinter import *
import time

root = Tk()
root.title("定时刷新颜色")
abc = ["red", "green", "blue", "indigo", "yellow"]
label = Label(root, text="COLOR")
label.pack()

def refresh(index=0):
    label.config(foreground=abc[index])
    index = (index + 1) % len(abc)
    root.after(1000, refresh, index)

root.after(1000, refresh)
mainloop()

修正后的代码中,我们只创建了一个Label,并在刷新函数中使用 label.config(foreground=abc[index]) 来设置Label的前景色属性。通过使用 index 变量来迭代颜色列表,我们可以在每次刷新时更新Label的前景色。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2023-8-18 14:56:05 | 显示全部楼层    本楼为最佳答案   
错误在于在刷新函数中,创建了多个Label,并且没有正确设置Label的前景色属性。下面是修正后的代码:
from tkinter import *
import time

root = Tk()
root.title("定时刷新颜色")
abc = ["red", "green", "blue", "indigo", "yellow"]
label = Label(root, text="COLOR")
label.pack()

def refresh(index=0):
    label.config(foreground=abc[index])
    index = (index + 1) % len(abc)
    root.after(1000, refresh, index)

root.after(1000, refresh)
mainloop()

修正后的代码中,我们只创建了一个Label,并在刷新函数中使用 label.config(foreground=abc[index]) 来设置Label的前景色属性。通过使用 index 变量来迭代颜色列表,我们可以在每次刷新时更新Label的前景色。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2023-8-18 14:56:13 | 显示全部楼层
Tkinter 定时刷新颜色 Python交流

你提供的代码有几个问题。下面是修改后的代码:
from tkinter import *import timeroot = Tk()root.title("定时刷新颜色")abc = ["red", "green", "blue", "indigo", "yellow"]color_index = 0def refresh():    global color_index    l.config(foreground=abc[color_index])    color_index = (color_index + 1) % len(abc)    root.after(1000, refresh)l = Label(root, text="COLOR")l.pack()root.after(1000, refresh)root.mainloop()
主要修改的地方有:

1. 添加了 global color_index,以确保在 refresh 函数中能够正确访问和更新 color_index 变量。

2. 将 l=Label(root,text="COLOR",foreground=abc) 修改为 l.config(foreground=abc[color_index]),这样可以动态改变标签的前景色。

3. 将 root.after(1000,refresh) 移出循环之外,放在末尾。这样在每次 refresh 函数执行完成后,都会再次调度一个新的刷新操作。

希望以上修改能够解决问题,使得标签的颜色能够按照指定的顺序定时刷新。如果还有其他问题,请随时提问。

如果回答对你有帮助,请给我一个最佳答案!
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-9-21 08:50

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表