Tkinter- 无法将图像与事件绑定

Tkinter- unable to bind image with an event

我创建了一个聊天应用程序,我也想在其中共享图像和图片,并且我在聊天框上显示图片一切都在进行到这里,但我想要当任何人点击显示的图像或图片时将为此在图像查看器中打开我从这个问题中得到了帮助并尝试了一些东西

当我 运行 代码图片在聊天框上显示后立即打开,但我想在有人单击时打开图片。 这是我的代码:

import functools
import json
import sys
from functools import partial
import tooltip as t
from tkinter import *
from upload import *
import PIL.Image
import PIL.ImageTk
import os
import pathlib
import cgitb
from tkinter import filedialog
from tkinter.filedialog import askopenfile
import threading
import ctypes
cgitb.enable ( )
class ChatInterface ( Frame ) :

  def __init__ ( self , master = None ) :
    Frame.__init__ ( self , master )
    self.imglist = [ ]
    self.master = master

    # sets default bg for top level windows


    self.text_frame = Frame ( self.master , bd = 6 , bg = "black" )
    self.text_frame.pack ( expand = True , fill = BOTH )

    self.text_box_scrollbar = Scrollbar ( self.text_frame , bd = 0 , bg = "#426CB4" )
    self.text_box_scrollbar.pack ( fill = Y , side = RIGHT )

    self.text_box = Text ( self.text_frame , yscrollcommand = self.text_box_scrollbar.set , state = DISABLED ,
                           bd = 1 , padx = 6 , pady = 6 , spacing3 = 8 , wrap = WORD , bg = "black" ,
                           font = "Times 10" , relief = GROOVE ,
                           width = 10 , height = 1 , fg = "white" )

    self.text_box.pack ( expand = True , fill = BOTH )
    self.text_box_scrollbar.config ( command = self.text_box.yview )

    self.entry_frame = Frame ( self.master , bd = 1 , bg = "black" )
    self.entry_frame.pack ( side = LEFT , fill = BOTH , expand = True )

    self.entry_field = Entry ( self.entry_frame , bd = 1 , justify = LEFT )

    self.entry_field.pack ( fill = X , padx = 6 , pady = 6 , ipady = 3 )



    self.upload_button_frame = Frame ( self.master , bd = 0 , bg = 'black' )
    self.upload_button_frame.pack ( fill = BOTH )

    self.pic_button = Button ( self.upload_button_frame , text = 'upload' ,
                               relief = GROOVE ,
                               borderwidth = 0 , bg = 'slateblue2' , bd = 0 , fg = "Black" ,
                               command = lambda : self.open_img ( ) , activebackground = "black" ,
                               activeforeground = "#000000" )
    self.pic_button.pack ( in_ = self.upload_button_frame , side = RIGHT )
    self.master.bind ( "<Return>" , self.open_img )
    self.pictccp = t.CreateToolTip ( self.pic_button , "Click here to share pictures" )






  def open_img ( self ) :

    global img
    tag = "imageclick"
    index = "2.0"
    f_types = [ ('Jpg Files' , '*.jpg') , ('Png Files' , '*.png') , ('Jpeg Files' , '*.jpeg') ]
    filename = filedialog.askopenfilename ( filetypes = f_types )
    file = pathlib.PurePath ( filename )
    fop = open ( file , "rb" )
    img = PIL.Image.open ( filename )
    img_resized = img.resize ( (200 , 100) )  # new width & height
    img = PIL.ImageTk.PhotoImage ( img_resized )

    self.text_box.configure ( state = NORMAL )
    self.text_box.image_create ( END , image = img )

    fop = open ( file , "rb" )

    def onclick ( ) :
      os.startfile ( file , 'open' )


    self.text_box.insert ( END , "\n" )

    self.text_box.bind ( "<Button-1>" , onclick ( ) )


    self.text_box.tag_configure ( "right" , justify = 'right' )
    self.text_box.tag_configure ( "right" , foreground = 'slate blue2' )
    self.text_box.tag_add ( "right" , 1.0 , "end" )
    self.text_box.configure ( state = DISABLED )
    self.text_box.see ( END )
    self.imglist.append ( img )








  

def chating ( ) :
  root = Tk()

  a = ChatInterface ( root )
  root.geometry ( "340x500" )
  root.title ( "Chat" )
  root.mainloop ( )

chating()

以下是在文本小部件中通过单击打开图像的一般解决方案示例:

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

这是你想要的吗?