0

I have a dropdown list. For each item I select from the dropdown, I was an image related to that item to show below the dropdown. I can do them separately but not sure how to put them together in tkinter

import tkinter as tk
from PIL import Image, ImageTk
fruitslist = [
    "apple",
    "orange",
    "grapes",
    "banana"
]

root = tk.Tk()

root.geometry('100x200')

def selc(event):
    if clicked.get() == "orange":
        img = ImageTk.PhotoImage(Image.open("image.jpg"))
        la.configure(image=img)
        la.image = img
    else:
        print("no image")
        
la = tk.Label(root, text="hi")

clicked = tk.StringVar(root)
clicked.set(fruitslist[0])

drop = tk.OptionMenu(root, clicked, *fruitslist, command = selc)
drop.pack()

root.mainloop()
Advik
  • 43
  • 9
  • Does this answer your question? [How to add an image in Tkinter?](https://stackoverflow.com/questions/10133856/how-to-add-an-image-in-tkinter) – YJJcoolcool Aug 30 '20 at 04:49

1 Answers1

2

You can set command to the OptionMenu and handle all the image change logic in the function based on the selection.

import tkinter as tk
from PIL import ImageTk, Image

fruitslist = [
    "apple",
    "orange",
    "grapes",
    "banana"
]

app = tk.Tk()

fruits_dict = {}
for fruit_name in fruitslist:
    fruits_dict[fruit_name] = ImageTk.PhotoImage(Image.open("{}.png".format(fruit_name)))

app.geometry('100x200')

variable = tk.StringVar(app)
variable.set(fruitslist[0])


def change_image(e):
    print(e)  # selected option
    # print(variable.get())  # Also you can retrieve selected option from the var
    # Change image here
    my_image.config(image=fruits_dict[e])


opt = tk.OptionMenu(app, variable, *fruitslist, command=change_image)
opt.config(width=90, font=('Helvetica', 12))
opt.pack()

my_image = tk.Label(app)
my_image.pack()

app.mainloop()
Marsilinou Zaky
  • 1,038
  • 7
  • 17