如何在tkinter中使用listbox查看图片?

问题描述 投票:1回答:1

如何使用Listbox显示图片(国旗)。图片是用python文件保存的。我在互联网上试了一些代码,但还是不成功。我在网上试了一些代码,还是没有成功,还是不能显示图片。

    def init_window(self):
        #Radiobutton codes here
        frmlist = Frame(self)
        self.lstcountry = Listbox(frmlist, font="Times 12", width=15, height=10)
        self.lstcountry.pack(side=LEFT)
        self.lstcountry.bind('<<ListboxSelect>>',self.changeCountry)
        scrollbar = Scrollbar(frmlist, orient=VERTICAL)
        scrollbar.pack(side=RIGHT, fill=Y)
        scrollbar.config(command=self.lstcountry.yview)
        frmlist.grid(row=0, rowspan=4, column=0)
        # add items in the listbox using insert()
        self.lstcountry.pack(side="left", fill=Y, expand=1)
        img = PhotoImage(file="Philippines.png")
        self.lab = Label(root, text="hello", image=img)
        self.pack()
    def changeContinents(self):
        self.lstcountry.delete(0, END)  # clear listbox
        continents = {"Asia": ["Malaysia", "Taiwan", "Singapore", "Philippines", "Thailand", "India"],
                  "Africa": ["Algeria", "Angola", "Egypt", "Cape Verde", "Liberia", "Kenya","Morocco", "Nigeria"],
                  "America": ["Venezuela", "Peru", "Jamaica", "United States", "Cuba", "Chile", "Argentina"],
                  "Europe": ["Russia", "Germany", "United Kingdom", "Italy", "Ukraine", "France", "Belgium"]}
        i = 0
        for countr in continents[self.v.get()]:
            self.lstcountry.insert(END, countr)
            i += 1
        self.lstcountry.selection_set(0)
    def changeCountry(self,event):
        try:
            n = self.lstcountry.curselection()
            countr = self.lstcountry.get(n)
            img = PhotoImage(file=(countr+'.png'))
        self.lab.config(image=img, bg = "blue")
            self.lab.image = img
            print(countr)
            self.pack()
        except:
          messagebox.showwarning("Image", "Image is not yet available")
    root = Tk()
    root.geometry("500x400")
    app = Window(root)
    root.mainloop()

在这个问题上有什么建议吗Thnaks。

python-3.x image tkinter listboxitem
1个回答
-1
投票

国家在 "Asia" 漏掉 "

你有

["Malaysia", "Taiwan", "Singapore", "Philippines", "Thailand", India"]

但应该是

["Malaysia", "Taiwan", "Singapore", "Philippines", "Thailand", "India"]

-1
投票

我忘了把self.lab.pack(side = "top")放进去了。

© www.soinside.com 2019 - 2024. All rights reserved.