You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将URL摄像头流拉取代码合并到现有Tkinter界面代码中

Tkinter界面整合URL摄像头流实现方案

核心修改说明

  • 补充urllib、numpy两个缺失的依赖导入
  • 替换原有cv2.imshow独立窗口逻辑,将视频帧直接渲染到Tkinter自带的Label组件中
  • 废弃while死循环拉流逻辑,改用Tkinter的after()定时调度方法拉取帧,避免阻塞Tkinter主界面的事件循环
  • 保留原有界面的背景、自定义按钮等全部控件,新增专门的视频流显示区域

完整合并代码

import tkinter as tk
from PIL import ImageTk, Image
import cv2
import urllib.request
import numpy as np

# 初始化主窗口
root = tk.Tk()
root.geometry("1920x1080+0+0") 

# 原有背景配置
background = ImageTk.PhotoImage(Image.open(r"D:\Telegrambotphotos\Ard.jpg")) 
rootBack = tk.Label(root, image=background) 
rootBack.place(x=0, y=0, width=1920, height=1080) 

# 新增视频流显示Label,可自行调整位置和尺寸
video_label = tk.Label(root)
video_label.place(x=100, y=100, width=800, height=600)
is_stream_running = False # 拉流状态标记

# 摄像头拉流逻辑
def on3_button():
    global is_stream_running
    is_stream_running = True
    # 替换为你自己的摄像头流地址
    url = '你的摄像头流URL'
    
    def update_frame():
        global is_stream_running
        if not is_stream_running:
            return
        # 拉流并解码
        img_resp = urllib.request.urlopen(url)
        img_np = np.array(bytearray(img_resp.read()), dtype=np.uint8)
        img = cv2.imdecode(img_np, -1)
        # 格式转换:OpenCV默认BGR格式转RGB,适配PIL
        img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        # 缩放到视频显示区域尺寸,避免溢出
        img_pil = Image.fromarray(img_rgb).resize((800, 600))
        imgtk = ImageTk.PhotoImage(image=img_pil)
        video_label.imgtk = imgtk # 保留图片引用,避免被GC回收导致不显示
        video_label.configure(image=imgtk)
        # 按q键停止拉流
        if cv2.waitKey(1) & 0xFF == ord('q'):
            is_stream_running = False
            video_label.configure(image='') # 清空显示区域
            return
        # 10ms后刷新下一帧,可调整数值修改刷新率
        video_label.after(10, update_frame)
    
    update_frame()

# 原有按钮配置,绑定点击触发拉流事件
photoSUp = ImageTk.PhotoImage(Image.open(r"E:\python\control interface\illis\mid-01.png")) 
rootMid = tk.Label(root, image=photoSUp) 
rootMid.place(x=1495, y=513) 
tk.Button(rootMid, image=photoSUp, command=on3_button).pack(side = tk.LEFT)

root.mainloop()
# 退出时销毁所有OpenCV窗口
cv2.destroyAllWindows()

注意事项

  • 本地文件路径前加r可以避免转义字符报错
  • 可自行修改video_label.place的参数调整视频显示的位置,修改resize的参数调整视频显示尺寸
  • 若拉流延迟过高,可适当调大after方法的毫秒参数,降低刷新率减少资源占用

内容的提问来源于stack exchange,提问作者Mahmoud Tamimi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 19:45:00