简体   繁体   English

我想在 tkinter 中显示图像

[英]I want an image to be displayed in tkinter

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 select,我是与该项目相关的图像以显示在下拉列表下方。 I can do them separately but not sure how to put them together in tkinter我可以单独做,但不确定如何在 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()

You can set command to the OptionMenu and handle all the image change logic in the function based on the selection.您可以将命令设置到OptionMenu并根据选择处理 function 中的所有图像更改逻辑。

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM