我试图通过调用另一个模块的函数,在主脚本创建的窗口中显示包含图像的小部件。 但我收到错误:
_tkinter.TclError:图像“pyimage1”不存在
此错误仅发生在包含图像的小部件中。
创建窗口并从模块调用函数的 main.py 脚本。
from customtkinter import *
import image_script
window = CTk()
window.geometry("1400x1000")
image_script.call_image()
window.mainloop()
image_script.py 包含创建和显示小部件的函数。
from customtkinter import *
from PIL import Image
def call_image():
from main import window
image_example = CTkImage(Image.open("images/icon_example.png"), size=(150, 100))
image_label = CTkLabel(window, image=image_example)
image_label.place(relx=0.5, rely=2, anchor="center")
仅较新版本的customtinker模块支持直接从图片路径打开图片。但这个新版本没有附带 python 标准库。需要安装。
Python 安装附带的 customtinker 模块是旧版本。无法直接从路径打开。它只能处理照片图像。此外,旧版本用于将图像添加到按钮和所有内容。
要处理按钮以外的照片图像,您不需要自定义tinker模块。你可以用 tkinter 本身来做到这一点。转换为 PhotoImage 是通过 PIL.ImageTk 完成的。
另一个问题:你已经使用了 place 方法并依赖=2,你已经给出了。依赖是相对 y 坐标。它的值介于 0 和 1 之间。如果你提到 2,它就会超出窗口。
另外,最好不要将图像路径声明为字符串。因为在windows操作系统中(如果项目在windows中使用),路径是用反斜杠()分隔的。而在基于 linux 和 unix 的操作系统中,它由正斜杠 (/) 分隔。这可以通过 python 的 os 模块使用 .path.join() 方法来处理。
代码应该是这样的:
main.py:
#main.py
from tkinter import *
from image_script import call_image
window = Tk()
window.geometry("1400x1000")
call_image(window)
window.mainloop()
#image_script.py
#image_script.py
from tkinter import *
import PIL.Image as im
import PIL.ImageTk as imgtk
import os
def call_image(window):
#get current working directory
cwd = os.getcwd()
#Assuming that the images folder is in your current working directory, get image_path
img_path = os.path.join(cwd, 'images', 'icon_example.png')
#open image with PIL.Image
img = im.open(img_path)
#Resize
img = img.resize((150,100))
#Convert into Photoimage using PIL.ImageTK
image_example = imgtk.PhotoImage(img)
#image label
image_label = Label(window, image=image_example)
#the following line is important as this function will be imported in main.py
#It prevents garbage_collection
image_label.photo = image_example
#Place image and label
image_label.place(relx=0.5, rely=0.5, anchor="center")
检查了虚拟图标图像并且工作完美。 看截图