B Hok
B Hok

Reputation: 155

Python 3 - Tcl/Tk how to get image from filedialog and display it?

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

Answers (1)

j_4321
j_4321

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

  • change the image of the button using the configure method

In 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

Related Questions