使用ImageTk.PhotoImage给tkinter添加图片不显示问题

from tkinter import Label, Tk

from PIL import Image, ImageTk


class App(Tk):

    def __init__(self):
        Tk.__init__(self)
        self.picture_display = Label(self)
        self.picture_display.pack()

    def show_slides(self):
        image_pil = Image.open('app/image/init.gif').resize((30, 30))
        self.image = ImageTk.PhotoImage(image_pil)
        self.picture_display.config(image=self.image)

    def run(self):
        self.mainloop()


app = App()
app.show_slides()
app.run()

ImageTk.PhotoImage(image_pil)需要使用self前缀修饰后,图片才能正常显示

  • 7
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您可以通过以下代码实现连续拍照,并以1、2、3等命名图片: ``` import cv2 import tkinter as tk from PIL import Image, ImageTk # 打开摄像头 cap = cv2.VideoCapture(0) # 创建GUI界面 root = tk.Tk() # 定义拍照函数 def take_picture(): global count ret, frame = cap.read() # 读取摄像头数据 cv2.imwrite(str(count) + ".jpg", frame) # 保存图片 count += 1 if count > 3: count = 1 img = Image.open(str(count) + ".jpg") # 打开图片 img = img.resize((400, 300), Image.ANTIALIAS) # 调整图片大小 photo = ImageTk.PhotoImage(img) # 转换为Tkinter可用的图片格式 label.configure(image=photo) # 更新Label显示图片 label.image = photo # 创建按钮 button = tk.Button(root, text="拍照", command=take_picture) button.pack() # 创建Label显示摄像头数据 label = tk.Label(root) label.pack() # 循环更新GUI界面 count = 1 while True: ret, frame = cap.read() # 读取摄像头数据 cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA) # 转换颜色格式 img = Image.fromarray(cv2image) # 转换为PIL可用的图片格式 img = img.resize((400, 300), Image.ANTIALIAS) # 调整图片大小 photo = ImageTk.PhotoImage(img) # 转换为Tkinter可用的图片格式 label.configure(image=photo) # 更新Label显示图片 label.image = photo root.update() # 更新GUI界面 # 释放摄像头资源 cap.release() # 关闭GUI界面 root.mainloop() ``` 在该代码中,我们添加了一个全局变量`count`,用于记录当前拍照的序号。在拍照时,我们将图片以序号命名并保存,然后更新`count`的值,以便下一次拍照使用。同时,我们将显示图片改为从文件中读取,以便实现连续拍照。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值