2016-12-13 321 views
0

我想爲一個任務做一個簡單的老虎機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'。 –

回答

0

的問題是,你在呼喚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

相關問題