如何解决如何在Tkinter中使图像可点击?
当前,该代码从文件夹中选择图像,并将其显示在tkinter窗口中。我可以单击“下一幅图像”以查看文件夹中的下一幅图像。我想使图像可点击,以便将我带到指定的链接。我可以使其单击,但不确定如何将不同的链接绑定到每个图像。如果我将图像随机化(计划以后再做),将会令人困惑
import tkinter as tk
from tkinter.filedialog import askdirectory
import os
img_list = []
def save_to_list(event):
click_loc = [event.x,event.y]
print ("you clicked on",click_loc)
img_list.append(click_loc)
def next_img():
img_label.img = tk.PhotoImage(file=next(imgs))
img_label.config(image=img_label.img)
root = tk.Tk()
root.geometry('500x500')
# Choose multiple images
img_dir = askdirectory(parent=root,initialdir="./yoga_Images/",title='Choose folder')
os.chdir(img_dir)
imgs = iter(os.listdir(img_dir))
img_label = tk.Label(root)
img_label.pack()
img_label.bind("<Button-1>",save_to_list)
btn = tk.Button(root,text='Next image',command=next_img)
btn.pack()
next_img()
root.mainloop()
解决方法
创建按钮时,您只需指定图像对象即可。
from PIL import Image,ImageTk
import tkinter as tk
def example():
print("Clickable Image!")
root = tk.Tk()
image = Image.open("image.png")
btnPhoto= ImageTk.PhotoImage(image)
imgBtn = tk.Button(root,image=btnPhoto,command=example)
imgBtn.pack()
root.mainloop()
如果您要制作多个可点击的图像,请使用以下代码,不要忘记指定图像目录(使用列表推导的道歉,我知道它们有些令人困惑)。
from PIL import Image,ImageTk
import tkinter as tk
import os
def example():
print("Clickable Image!")
root = tk.Tk()
imgDir = "imgs"
images = [ImageTk.PhotoImage(Image.open(os.path.join(imgDir,imgName))) for imgName in os.listdir(imgDir)]
for img in images:
imgBtn = tk.Button(root,image=img,command=example)
imgBtn.pack()
root.mainloop()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。