2016-06-12 9 views
0

現在、リターンキーへのバインディングを使用して、tkinterラベルウィジェットの画像を変更しようとしています。戻るキーを押した後、イメージが "im2"に変わり、2秒待ってから再び "im3"に変更します。私がこれまで使っ コードは次のようになります。しかし、その代わりに二回、それが唯一の「IM3」に一度変更された画像を変更する2秒のリターンを押した後、その何とか最初の変更が表示されていない関数呼び出し後にラベル内の画像が変更されない

window = tk.Tk() 
window.title("Testwindow") 
window.geometry("800x800") 
window.configure(background='grey') 

# images 
im1_path = "im1.gif" 
im2_path = "im2.gif" 
im3_path = "im3.gif" 
im1 = ImageTk.PhotoImage(Image.open(im1_path)) 
im2 = ImageTk.PhotoImage(Image.open(im2_path)) 
im3 = ImageTk.PhotoImage(Image.open(im3_path)) 

panel = tk.Label(window, image = im1) 
panel.pack(side = "bottom", fill = "both", expand = "yes") 

def callback(e): 
    panel.configure(image = im2) 
    panel.image = im2 

    time.sleep(2) 

    panel.configure(image = im3) 
    panel.image = im3 

window.bind("<Return>", callback) 
window.mainloop() 

。なぜ誰が知っていますか?

+0

変更は、それがあなたのコードを実行しているとして、UIには反映されません。更新は 'mainloop()'でのみ起こります。 – msw

+1

http://stackoverflow.com/questions/30284270/why-does-time-sleep-pause-tkinter-window-before-it-opensおよびhttp://stackoverflow.com/questions/33175457/time-sleepも参照してください。 -equivalent-on-tkinter –

+0

@ PM2Ring、ありがとう! –

答えて

4

time.sleep()はプログラムの実行を停止するのでここでは機能しません。after ...を使用する必要があります。また、GUIプログラミングでsleepを使用することは悪い習慣です。

root.after(time_delay, function_to_run, args_of_fun_to_run)

だからあなたの場合にはそれが

def change_image(): 
    panel.configure(image = im3) 
    panel.image = im3 

を気に入るだろうし、あなたのコールバック関数に

def callback(e): 
    panel.configure(image = im2) 
    panel.image = im2 
    #after 2 seconds it'll call the above function 
    window.after(2000, change_image) 
関連する問題