How to make Clickable Image in python

后端 未结 1 459
长情又很酷
长情又很酷 2021-01-25 06:29

I am a beginner in python image programming. If I click the image I need to display you are clicked image 1. like that. what I tried so far I attached below. It is not working a

相关标签:
1条回答
  • Take a look at this example

    Here you can click the button and it gives you an effect of clicking the image.

    from tkinter import *
    from tkinter import messagebox
    from PIL import Image, ImageTk
    
    root = Tk()
    canvas = Canvas(root, width=600, height=600)
    canvas.pack()
    
    def main(event):
        if event.widget.cget('image') == 'pyimage1':
            messagebox.showinfo('First','You clicked the first image')
        elif event.widget.cget('image') == 'pyimage2':
            messagebox.showinfo('Second','You clicked the second image')
        elif event.widget.cget('image') == 'pyimage3':
            messagebox.showinfo('Third','You clicked the third image')
    
    img_file = Image.open("sad songs.jpg")
    img_file = img_file.resize((150, 150))
    img = ImageTk.PhotoImage(img_file)
    b1 = Button(canvas, image=img)
    b1.pack()
    b1.bind('<Button-1>', main)
    
    
    img_file1 = Image.open("feeling wallpapers.jpg")
    img_file1 = img_file1.resize((150, 150))
    img1 = ImageTk.PhotoImage(img_file1)
    b2 = Button(canvas, image=img1)
    b2.pack()
    b2.bind('<Button-1>', main)
    
    img_file2 = Image.open("sad songs.jpg")
    img_file2 = img_file2.resize((150, 150))
    img2 = ImageTk.PhotoImage(img_file2)
    b3 = Button(canvas, image=img2)
    b3.pack()
    b3.bind('<Button-1>', main)
    
    root.mainloop()
    

    Hope it helped you

    Cheers

    0 讨论(0)
提交回复
热议问题