如何动态更新tkinter标签小部件中的图像?

问题描述:

我想为一个任务做一个简单的*python程序,我无法获得*图像更新。我想要发生的事情是让用户点击按钮,让三个标签每隔0.1秒动态更新一张不同的图片,持续2秒。但是,发生了什么事是我的randint正在为数组生成随机索引号,但标签只在最后一个randint实例上显示一个新图像。这里是我的代码:如何动态更新tkinter标签小部件中的图像?

def update_image(): 
     global images 
     time.sleep(0.1) 
     y = images[randint(0, 3)] 
     slot1.delete() 
     slot1.configure(image = y) 
     print(y) 

def slot_machine(): 
     x = 0 
     while x != 10: 
       slot1.after(0,update_image) 
       x = x + 1 
+0

你为什么叫'slot1.after(0,...)'然后立即在'update_image'中睡十分之一秒?为什么不直接调用'slot1.after(100,...)'?一般来说,你不应该在主GUI线程中调用'sleep'。 –

的问题是,你在呼唤after(0, ...)这增加了工作的“后”队列中尽快运行。但是,while循环运行速度极快,并且从不给事件循环处理排队事件的机会,因此整个循环在单个图像更改之前结束。

一旦事件循环能够处理事件,tkinter将尝试处理所有未过期的未决事件。由于您使用了零超时,所以它们都会过期,因此tkinter会尽可能快地运行它们。

更好的解决方案是让更新映像的函数也负责调度下一次更新。例如:

def update_image(delay, count): 
    <your existing code here> 

    # schedule the next iteration, until the counter drops to zero 
    if count > 0: 
     slot1.after(delay, update_image, delay, count-1) 

就这样,你怎么称呼它一次,然后它经过反复调用自身:

update_image(100, 10) 
+0

这真棒!谢谢! – MustardFacial