Reputation: 155
I'm trying to select a file from the filedialog and have the picture shown in the GUI
def onOpen():
""" Ask the user to choose a file and change the update the value of photo"""
photo= get(filedialog.askopenfilename())
photo2 = PhotoImage(filedialog=photo)
#how do I get photo2 to work and get button to display the picture?
button = Button(root, image=photo2, text="click here", command=onOpen).grid()
root.mainloop()
Upvotes: 1
Views: 4763
Reputation: 16169
What you want to achieve can be done in three steps:
get the path of the picture chosen by the user
filename = filedialog.askopenfilename()
create the PhotoImage
configure
methodIn addition, you need to make the variable containing the PhotoImage
global so that it is not garbage-collected.
import tkinter as tk
from tkinter import filedialog
def onOpen():
global photo
filename = filedialog.askopenfilename()
photo = tk.PhotoImage(file=filename)
button.configure(image=photo)
root = tk.Tk()
photo = tk.PhotoImage(file="/path/to/initial/picture.png")
button = tk.Button(root, image=photo, command=onOpen)
button.grid()
root.mainloop()
Upvotes: 1