2014-10-27 66 views
0

如下所示,我想使用tkinter在畫布上顯示圖像,當點擊按鈕時,應該顯示其他照片。但我失敗了。第一張圖片顯示效果不錯,但當單擊按鈕時,圖片沒有變化如何更改畫布中的圖像?[python tkinter]

C = Tkinter.Canvas(top, bg="#fff", height=500, width=600) 

// show image1 in canvas first and it works 
itk = ImageTk.PhotoImage(img1) 
C.create_image(300, 250, image=itk) 
C.pack() 


def changeImage(): 
    // I want to show image2 in canvas, but I fails 
    print 'change image in canvas' 
    itk2 = ImageTk.PhotoImage(img2) 
    C.create_image(300, 250, image=itk2) 

button = Tkinter.Button(top,text='click', command=changeImage) 
button.pack() 


top.mainloop() 

回答

1

更改所有匹配項目的一個或多個選項。 1

myimg = C.create_image(300, 250, image=itk) 

def changeImage(): 
    // I want to show image2 in canvas, but I fails 
    print 'change image in canvas' 
    itk2 = ImageTk.PhotoImage(img2) 
    C.itemconfigure(myimg, image=itk2) 
+0

對不起,我添加後不起作用 – user2666750 2014-10-27 12:50:04

0

itk2被破壞,一旦退出函數(你將獲得代碼的其他行語法錯誤)。其中一個解決方案是將其保留在功能之外。考慮這個僞代碼,因爲我沒有時間去測試它。

class ImageTest(): 
    def __init__(self): 
     self.root = tk.Tk() 

     self.root.title('image test') 
     self.image1 = ImageTk.PhotoImage(img1) 
     self.image2 = ImageTk.PhotoImage(img2) 

     self.displayed=True 
     self.panel1 = Tkinter.Canvas(top, bg="#fff", height=500, width=600) 
     self.panel1.create_image(300, 250, image=self.image1) 
     self.panel1.pack() 


     tk.Button(self.root, text="Next Pic", command=self.callback, 
       bg="lightblue").pack() 
     tk.Button(self.root, text="Exit", command=quit, bg="red").pack() 

     self.root.mainloop() 

    def callback(self): 
     if self.displayed: 
      self.panel1["image"]=self.image2 
     else: 
      self.panel1.config(image=self.image1) 
     self.displayed=not self.displayed 

IT=ImageTest()