so i have this simple app to upload image but now i want every time i upload a new image, the previous image get cleared. Looking for the solution, thanks in advance.
def open():
global my_image
root.filename = filedialog.askopenfilename(initialdir="e:/images", title="Select A File",
filetypes=(("png files", "*.png"), ("all files", "*.*")))
my_label = Label(root, text=root.filename).pack()
my_image = ImageTk.PhotoImage(Image.open(root.filename))
my_image_label = Label(image=my_image).pack()
my_btn = Button(root, text="Open File", command=open).pack()
You have to define the labels outside the function and update it inside the function, this will avoid over-writing the labels with new data each time. Take a look here:
# Define the labels initially
my_image_label = Label(root)
my_label = Label(root)
def open_img():
path = filedialog.askopenfilename(initialdir="e:/images", title="Select A File",
filetypes=(("png files", "*.png"), ("all files", "*.*")))
my_label.config(text=path) # Update the label with the path
my_label.pack() # Pack it in there
my_image = ImageTk.PhotoImage(file=path) # Make an ImageTk instance
my_image_label.config(image=my_image) # Update the image label
my_image_label.pack() # Pack the label
my_image_label.img = my_img # Keep reference to the image
my_btn = Button(root, text="Open File", command=open_img)
my_btn.pack()
What all have I changed?
I used the config()
method of widgets helps you to edit the options of the widgets.
I have also removed the usage of Image.open()
as you can achieve the same by using file
keyword argument of ImageTk.PhotoImage
, it calls Image.open()
implicitly.
Also I removed global
and kept a reference to the image.
I also renamed some variables and changed the name of you're function, as open()
will over ride the built-in open()
function of python.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.