我正在编写一个类似记事本的项目,我需要将图像插入到 Tkinter 文本小部件中(就像 MS Word 所做的那样),但我没有找到任何帮助我解决这个问题的东西。
这是我的代码:
from PIL import Image,ImageTk
from tkinter import *
text = Text(root)
root.pack()
#Insert Image
yourImage=filedialog.askopenfilename(title = "Select your image",filetypes = [("Image Files","*.png"),("Image Files","*.jpg")])
imgFile=Image.open(yourImage)
imgToInsert=ImageTk.PhotoImage(imgFile)
text.image_create("current",image=imgToInsert)
Run Code Online (Sandbox Code Playgroud)
但是当我运行它时,它只显示一个白色的图像,上面什么都没有。
我的代码有什么问题?有人可以向我解释一下吗
您可以使用image_create
或window_create
使用两者的示例
此示例不使用 PIL,仅使用 PhotoImage,它只能获取 gif 图像文件。
示例代码:
import tkinter as tk
def add_image():
text.image_create(tk.END, image = img) # Example 1
text.window_create(tk.END, window = tk.Label(text, image = img)) # Example 2
root = tk.Tk()
text = tk.Text(root)
text.pack(padx = 20, pady = 20)
tk.Button(root, text = "Insert", command = add_image).pack()
img = tk.PhotoImage(file = "myImage.gif")
root.mainloop()
Run Code Online (Sandbox Code Playgroud)
此外,在您的代码中,我没有看到您如何使用所选图像。yourImage
未在任何地方使用
归档时间: |
|
查看次数: |
10370 次 |
最近记录: |