通过按钮选择图像在标签上显示图像

时间:2019-06-03 11:05:38

标签: python tkinter

单击该按钮时,应弹出浏览窗口,要求选择图像文件,并且该图像需要显示在标签上。无法定义函数clicked()

from tkinter import *
from PIL import Image, ImageTk
from tkinter import filedialog
from tkinter.filedialog import askopenfilename

root = Tk()

#def clicked():
#   path=filedialog.askopenfilename(filetypes=[("Image File",'.jpg')])

label = Label(root, image = logo)
label.pack()

button = Button(root, text = "Load Image", command = clicked)
button.pack()

root.mainloop()

1 个答案:

答案 0 :(得分:0)

这可能对您有帮助

 from tkinter import *
 from tkinter import filedialog
 from PIL import  Image,ImageTk


   class GUI(Frame):

def __init__(self, master=None):
    Frame.__init__(self, master)
    w,h = 650, 650
    master.minsize(width=w, height=h)
    master.maxsize(width=w, height=h)
    self.pack()

    self.file = Button(self, text='Browse', command=self.choose)
    self.choose = Label(self, text="Choose file").pack()
    #Replace with your image
    self.image = PhotoImage(file='test.png')
    self.label = Label(image=self.image)


    self.file.pack()
    self.label.pack()

def choose(self):
    ifile = filedialog.askopenfile(parent=self,mode='rb',title='Choose a file')
    path = Image.open(ifile)

    self.image2 = ImageTk.PhotoImage(path)
    self.label.configure(image=self.image2)
    self.label.image=self.image2


  root = Tk()
  app = GUI(master=root)
  app.mainloop()
  root.destroy()