微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在python中制作可点击图片

如何解决如何在python中制作可点击图片

我是python图像编程的初学者。如果我单击要显示的图像,则单击图像1。 像那样。到目前为止我尝试过的内容附在下面。 img 1,img 1,img 1总是显示不正常的答案

from tkinter import *
from tkinter import messageBox

from PIL import Image,ImageTk

root = Tk()
canvas = Canvas(root,width=600,height=600)
canvas.pack()

def click() :
    canvas.img = img
    canvas.img1 = img1
    canvas.img2 = img2

    if(canvas.img):
        print("img 1")
    elif(canvas.img1):
        print("2")
    else :
        print("3")

img_file = Image.open("1.jpg")
img_file = img_file.resize((150,150) )
img = ImageTk.PhotoImage(img_file )
canvas.create_image(10,50,anchor=NW,image=img)


img_file1 = Image.open("2.jpg")
img_file1 = img_file1.resize((150,150))
img1 = ImageTk.PhotoImage(img_file1)
canvas.create_image(200,image=img1)

img_file2 = Image.open("3.jpg")
img_file2 = img_file2.resize((150,150))
img2 = ImageTk.PhotoImage(img_file2)
canvas.create_image(400,image=img2)

Button(root,text="Add",command = click,height=3,width= 13).place(x=190,y=260)



root.mainloop()

解决方法

看看这个例子

在这里您可以单击按钮,它给您单击图像的效果。

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

希望对您有帮助

欢呼

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。