2010-08-14 14 views
18

Bir Tkinter etiketinde bir görüntüyü takas edebilmeyi isterim ancak widget'ın değiştirilmesi dışında, nasıl yapılacağından emin değilim.Tkinter Label widget'ının görüntüsü nasıl güncellenir?

Şu anda, şöyle bir görüntü gösterebilir: kullanıcının ziyaret, ENTER anahtarı derken

import Tkinter as tk 
import ImageTk 

root = tk.Tk() 
img = ImageTk.PhotoImage(Image.open(path)) 
panel = tk.Label(root, image = img) 
panel.pack(side = "bottom", fill = "both", expand = "yes") 
root.mainloop() 

Ancak, ben imajını değiştirmek istiyorum.

import Tkinter as tk 
import ImageTk 

root = tk.Tk() 

img = ImageTk.PhotoImage(Image.open(path)) 
panel = tk.Label(root, image = img) 
panel.pack(side = "bottom", fill = "both", expand = "yes") 

def callback(e): 
    # change image 

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

Bu mümkün mü?

cevap

29

yöntemi panel.configure(image=img) içinde çalışır.

Çöp toplamanın görüntüyü silmesini engellemek için ne yapmayı unuttum panel.image=img'u dahil etmekti.

import Tkinter as tk 
import ImageTk 


root = tk.Tk() 

img = ImageTk.PhotoImage(Image.open(path)) 
panel = tk.Label(root, image=img) 
panel.pack(side="bottom", fill="both", expand="yes") 

def callback(e): 
    img2 = ImageTk.PhotoImage(Image.open(path2)) 
    panel.configure(image=img2) 
    panel.image = img2 

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

görüntü küresel değişkeni img depolandığı için orijinal kod çalışır:

şu yeni versiyonu.

+0

Geri aramadaki satır 'panel.image = img2' okuyor mu? – 101

+0

@figs, bu mantıklı olurdu. Bu kullanımı özellikle değiştirmek zorunda olduğumu hatırlamıyorum, ancak bu da dört yıldan fazla bir süredir. Doğrulamak için test edebilir misiniz? – skeggse

+0

Evet, muhtemelen sorun buydu. Biraz farklı kodlarla test edildi, ancak aynı sorunla. –

0

Bunu yapmak için başka bir seçenek.

Nesne yönelimli programlama ve görüntüyü güncellemek için etkileşimli bir arabirim kullanarak.

from Tkinter import * 
import tkFileDialog 
from tkFileDialog import askdirectory 
from PIL import Image 

class GUI(Frame): 

    def __init__(self, master=None): 
     Frame.__init__(self, master) 
     w,h = 650, 650 
     master.minsize(width=w, height=h) 
     master.maxsize(width=w, height=h) 
     self.pack() 

     self.file = Button(self, text='Browse', command=self.choose) 
     self.choose = Label(self, text="Choose file").pack() 
     self.image = PhotoImage(file='cualitativa.gif') 
     self.label = Label(image=self.image) 


     self.file.pack() 
     self.label.pack() 

    def choose(self): 
     ifile = tkFileDialog.askopenfile(parent=self,mode='rb',title='Choose a file') 
     path = ifile.name 
     self.image2 = PhotoImage(file=path) 
     self.label.configure(image=self.image2) 
     self.label.image=self.image2 


root = Tk() 
app = GUI(master=root) 
app.mainloop() 
root.destroy() 

Kullanmak istediğiniz varsayılan görüntü için 'cualitativa.jpg' yerine.