2017-05-26 9 views
0

ボタンを押したときに2つの画像を表示したい。私は2つの画像と対応する2つのボタンを持っています。私は、パネルのconfigure関数を使って画像を変更しようとしていますが、無駄にしています。私はこれをどのように実現するのでしょうか?ありがとうございました!ボタンで画像を変更するPython Tkinterでクリックする

import Tkinter as tk 
from PIL import ImageTk, Image 

def next(panel): 
    path = "2.jpg" 
    img = ImageTk.PhotoImage(Image.open(path)) 
    panel.configure(image=img) 
    panel.image = img # keep a reference! 

def prev(panel): 
    path = "1.jpg" 
    img = ImageTk.PhotoImage(Image.open(path)) 
    panel.configure(image=img) 
    panel.image = img # keep a reference! 

#Create main window 
window = tk.Tk() 

#divide window into two sections. One for image. One for buttons 
top = tk.Frame(window) 
top.pack(side="top") 
bottom = tk.Frame(window) 
bottom.pack(side="bottom") 

#place image 
path = "1.jpg" 
img = ImageTk.PhotoImage(Image.open(path)) 
panel = tk.Label(window, image = img) 
panel.image = img # keep a reference! 
panel.pack(side = "top", fill = "both", expand = "yes") 


#place buttons 
prev_button = tk.Button(window, text="Previous", width=10, height=2, command=prev(panel)) 
prev_button.pack(in_=bottom, side="left") 
next_button = tk.Button(window, text="Next", width=10, height=2, command=next(panel)) 
next_button.pack(in_=bottom, side="right") 

#Start the GUI 
window.mainloop() 

答えて

1

ボタンのコールバックコマンドに引数を渡すには、関数は、ボタンの作成時に呼び出される他、lambdaキーワードを必要としています。

#place buttons 
prev_button = tk.Button(window, text="Previous", width=10, height=2, command=lambda: prev(panel)) 
prev_button.pack(in_=bottom, side="left") 
next_button = tk.Button(window, text="Next", width=10, height=2, command=lambda: next(panel)) 
next_button.pack(in_=bottom, side="right") 
関連する問題