Actually an application using Tkinter and Python and now I am facing some issues. I want that when I Choose the Button a dialog appears and it select image and then change the default avatar to the selected one but I am unable to do so , If any One have any Idea what to do in such situation it is appreciated
from pathlib import Path
from tkinter import Tk, Canvas, Entry, Text, Button, PhotoImage,filedialog,Label
from PIL import ImageTk, Image
OUTPUT_PATH = Path(__file__).parent
ASSETS_PATH = OUTPUT_PATH / Path(r"D:/projects/notes app/common assets file")
def relative_to_assets(path: str) -> Path:
return ASSETS_PATH / Path(path)
def choose_image():
file_path = filedialog.askopenfilename(title="Select Image", filetypes=[("Image Files", "*.png;*.jpg;*.jpeg")])
if file_path:
new_avatar_image = Image.open(file_path)
# Save the selected image to the assets directory
new_avatar_path = relative_to_assets("selected_avatar.png")
new_avatar_image.save(new_avatar_path)
# Update the avatar image on the canvas with the selected image
canvas.itemconfig(avatar, image=ImageTk.PhotoImage(new_avatar_image))
window = Tk()
window.geometry("885x575")
window.configure(bg = "#DFD9D9")
canvas = Canvas(
window,
bg = "#DFD9D9",
height = 575,
width = 885,
bd = 0,
highlightthickness = 0,
relief = "ridge"
)
canvas.place(x = 0, y = 0)
canvas.create_text(
127.0,
63.0,
anchor="nw",
text="Add an Avatar or Profile Picture ",
fill="#1E1E1E",
font=("Sora Regular", 40 * -1)
)
default_avatar_path = relative_to_assets("avatar.png")
avatar_image = Image.open(default_avatar_path)
avatar_photo = ImageTk.PhotoImage(avatar_image)
avatar = canvas.create_image(442.0, 254.0, image=avatar_photo)
entry_image_1 = PhotoImage(
file=relative_to_assets("entry_1.png"))
entry_bg_1 = canvas.create_image(
442.5,
404.5,
image=entry_image_1
)
entry_1 = Entry(
bd=0,
bg="#A1A1A1",
fg="#000716",
highlightthickness=0
)
entry_1.place(
x=201.0,
y=384.0,
width=483.0,
height=39.0
)
button_image_1 = PhotoImage(
file=relative_to_assets("next.png"))
button_1 = Button(
image=button_image_1,
borderwidth=0,
highlightthickness=0,
command=lambda: print("Move to Next Page"),
relief="flat"
)
button_1.place(
x=725.0,
y=508.0,
width=134.0,
height=43.0
)
button_image_2 = PhotoImage(
file=relative_to_assets("back.png"))
button_2 = Button(
image=button_image_2,
borderwidth=0,
highlightthickness=0,
command=lambda: print("Go Backwards"),
relief="flat"
)
button_2.place(
x=571.0,
y=507.0,
width=134.0,
height=44.0
)
button_image_3 = PhotoImage(
file=relative_to_assets("choose.png"))
button_3 = Button(
image=button_image_3,
borderwidth=0,
highlightthickness=0,
command=choose_image,
relief="flat"
)
button_3.place(
x=565.0,
y=384.0,
width=129.0,
height=41.0
)
window.resizable(False, False)
window.mainloop()
This is The Complete Code of My project and I have Used Pathlib to manage the file on Cross platform like Linux and Windows These are the images which is being used