Not able to read .png/.jpg from directory into the insert_picture() function instead of writing the name of .png/.jpg each time

41 views Asked by At

I want to use the insert_picture() function and insert pictures into placeholders. But I don't want to type the name of the picture (e.g., insert_picture(xyz.png)) but let python read the filename and insert it into the insert_picture() function. For example, insert_picture(/Users/xyz/Documents/filename...).

and I want for placeholder.insert_picture(read the filename instead of writing it myself).

I don't know where to start.

1

There are 1 answers

0
toyota Supra On

but let python read the filename and insert it into the insert_picture() function. For example, insert_picture(/Users/xyz/Documents/filename...)

Try this example.

  • Add module from tkinter.filedialog import askopenfilename
  • Add Button widget.

Snippet:

import tkinter as tk
from tkinter.filedialog import askopenfilename
 

root = tk.Tk()
root.geometry("200x200+750+400")

b = tk.Button(root, text='IMAGES', command=lambda:upload_file())
b.pack()

def upload_file():
    f_types=[('png Files', '*.png'), ('Jpg Files', '*.png')]
    filename=tk.filedialog.askopenfilename(filetypes=f_types)
    img = tk.PhotoImage(file=filename)
    e1 = tk.Button(root)
    e1.pack()
    e1.image=img
    e1['image'] = img
    
root.mainloop()