[英]Tkinter : How to insert an image to a text widget
我正在編寫一個類似記事本的項目,我需要將圖像插入到 Tkinter Text 小部件(就像 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)
您可以同時使用
image_create<\/code>或
window_create<\/code>示例
此示例不使用 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()
我希望這可以幫助你。
from PIL import Image,ImageTk
from tkinter import *
from tkinter import filedialog
root=Tk()
text = Text(root)
text.pack()
#Insert Image
yourImage=filedialog.askopenfilename(title = "Select your image",filetypes = [("Image Files","*.png"),("Image Files","*.jpg")])
#imgFile=Image.open(yourImage)
imgToInsert=ImageTk.PhotoImage(file=yourImage)
text.image_create("current",image=imgToInsert)
root.mainloop()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.