Reputation: 43
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()
Upvotes: 0
Views: 358
Reputation: 1047
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()
Upvotes: 2