Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
204 views
in Technique[技术] by (71.8m points)

python - Upload image by clearing previous image

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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...