Resim gösterici label silme

from tkinter import *

from PIL import ImageTk, Image
from tkinter import filedialog
import os

root = Tk()
root.geometry(“550x300+300+150”)
root.resizable(width=True, height=True)

def openfn():
filename = filedialog.askopenfilename(title=‘open’)
return filename
def open_img():
x = openfn()
img = Image.open(x)
img = img.resize((250, 250), Image.ANTIALIAS)
img = ImageTk.PhotoImage(img)
panel = Label(root, image=img)
panel.image = img
panel.pack()

btn = Button(root, text=‘open image’, command=open_img).pack()

root.mainloop()

yeni bir resim açmak istediğimde bir alta yeni bir label olşturuyor. resimlerin üst üste veya sütun olmasını değil tek öğede olmasını nasıl sağlarım

Merhaba,

Kodlarınıza kod görünümü nasıl kazandırılır öğrenmek için aşağıdaki bağlantıyı ziyaret edin lütfen.

Ayrıca PhotoImage’i local alanda değil de global alanda tanımlamanız gerekiyor.

from tkinter import *
from PIL import ImageTk, Image
from tkinter import filedialog
import os

root = Tk()
root.geometry("550x300+300+150")
root.resizable(width=True, height=True)

PhotoImage()

def openfn():
    filename = filedialog.askopenfilename(title='open')
    return filename

def open_img():
    x = openfn()
    img = Image.open(x)
    img = img.resize((250, 250), Image.ANTIALIAS)
    img = ImageTk.PhotoImage(img)
    panel = Label(root, image=img)
    panel.image = img
    panel.pack()

btn = Button(root, text='open image', command=open_img).pack()

root.mainloop()

şeklinde yaptım ama değişen birşey olmadı. doğrusunu yazarmısınız.

Önce global alanda PhotoImage sınıfından bir örnek oluşturun. İsmi örneğin img olsun. file parametresine mevcut olan bir resmin adresini yazın ama bu resim label widgetinin image parametresinin değeri olmasın. Daha sonra da düğmeye her bastığınızda global alandaki img değişkenini kullanarak Label'a resmi ekleyebilirsiniz.

Aşağıdaki kodları bir inceleyin isterseniz:

from tkinter import *

from PIL import ImageTk, Image
from tkinter import filedialog

root = Tk()
root.geometry("550x300+300+150")
root.resizable(width=True, height=True)

panel = Label(root)
panel.pack()

        
def select_img():
    global img
    filename = filedialog.askopenfilename(title="open")
    open_img = Image.open(filename)
    open_img = open_img.resize((250, 250), Image.ANTIALIAS)
    open_img.save(filename, "JPEG")
    img = ImageTk.PhotoImage(file=filename)
    panel.configure(image=img)


# PhotoImage'i ilklendirmek için
# Geçici olarak bir resim tanımlayın.
img = ImageTk.PhotoImage(file="Geçici resmin adresi.")

btn = Button(root, text="open image", command=select_img).pack()

root.mainloop()