Tkinter- 无法将图像与事件绑定
Tkinter- unable to bind image with an event
以下是在文本小部件中通过单击打开图像的一般解决方案示例:
import tkinter as tk
from PIL import ImageTk, Image
import os
root = tk.Tk()
text = tk.Text(root, padx=10, pady=5, cursor ="hand2")
text.pack(padx=10, pady=10)
tag_dict = dict() # Holds path to images in the Text widget
def click(tag):
print(f'Clicked on {tag}')
info = tag_dict.get(tag, False)
if info:
cwd = os.getcwd()
filepath = os.path.join(cwd, info)
os.startfile(filepath) # Start default program and load image
# Add some text and tag it
tag = 'Text1'
text.insert(tk.END, "The first text\n", tag)
text.tag_bind(tag, "<Button-1>", lambda event, tag=tag: click(tag))
# Add an image and tag it
pilimg = Image.open('images/chapman.png') # Relative path to image file
image1 = ImageTk.PhotoImage(pilimg)
image_start_index = text.index(tk.INSERT) # Save INSERT index before image
tag = "Image1"
tag_dict[tag] = 'images/chapman.png' # Save file path to tag_dict
imgname = text.image_create(tk.END, image=image1)
image_stop_index = text.index(tk.INSERT) # Save INSERT index after image
text.tag_add(tag, image_start_index, image_stop_index) # Tag image
text.tag_bind(tag, "<Button-1>", lambda event, tag=tag: click(tag))
text.insert(tk.END, "\n") # Add newline after image
# Add some text and tag it
tag = 'Text2'
text.insert(tk.END, "The second text\n", tag)
text.tag_bind(tag, "<Button-1>", lambda event, tag=tag: click(tag))
root.mainloop()
这是你想要的吗?
以下是在文本小部件中通过单击打开图像的一般解决方案示例:
import tkinter as tk
from PIL import ImageTk, Image
import os
root = tk.Tk()
text = tk.Text(root, padx=10, pady=5, cursor ="hand2")
text.pack(padx=10, pady=10)
tag_dict = dict() # Holds path to images in the Text widget
def click(tag):
print(f'Clicked on {tag}')
info = tag_dict.get(tag, False)
if info:
cwd = os.getcwd()
filepath = os.path.join(cwd, info)
os.startfile(filepath) # Start default program and load image
# Add some text and tag it
tag = 'Text1'
text.insert(tk.END, "The first text\n", tag)
text.tag_bind(tag, "<Button-1>", lambda event, tag=tag: click(tag))
# Add an image and tag it
pilimg = Image.open('images/chapman.png') # Relative path to image file
image1 = ImageTk.PhotoImage(pilimg)
image_start_index = text.index(tk.INSERT) # Save INSERT index before image
tag = "Image1"
tag_dict[tag] = 'images/chapman.png' # Save file path to tag_dict
imgname = text.image_create(tk.END, image=image1)
image_stop_index = text.index(tk.INSERT) # Save INSERT index after image
text.tag_add(tag, image_start_index, image_stop_index) # Tag image
text.tag_bind(tag, "<Button-1>", lambda event, tag=tag: click(tag))
text.insert(tk.END, "\n") # Add newline after image
# Add some text and tag it
tag = 'Text2'
text.insert(tk.END, "The second text\n", tag)
text.tag_bind(tag, "<Button-1>", lambda event, tag=tag: click(tag))
root.mainloop()
这是你想要的吗?