# coding:utf-8
import cv2
import tkinter as tk
from tkinter import ttk, messagebox
def list_cameras():
index = 0
arr = []
while True:
cap = cv2.VideoCapture(index, cv2.CAP_DSHOW)
if not cap.isOpened():
break
else:
arr.append(index)
cap.release()
index += 1
return arr
def show_frame():
global cap, camera_running
if camera_running:
ret, frame = cap.read()
if ret:
cv2.imshow("Capture_Paizhao", frame)
cv2.waitKey(1)
root.after(10, show_frame)
else:
cap.release()
cv2.destroyAllWindows()
def start_camera(camera_index):
global cap, camera_running
cap = cv2.VideoCapture(camera_index, cv2.CAP_DSHOW)
if not cap.isOpened():
messagebox.showerror("Error", "无法打开摄像头")
return
camera_running = True
show_frame()
def stop_camera():
global camera_running
camera_running = False
def on_start_button_click():
global camera_running
if camera_running:
stop_camera()
start_button.config(text="直播")
else:
selected_index = camera_combobox.current()
if selected_index == -1:
messagebox.showwarning("Warning", "请选择一个摄像头")
else:
camera_index = cameras[selected_index]
start_camera(camera_index)
start_button.config(text="停止")
# 创建主窗口
root = tk.Tk()
root.title("Camera Selector")
# 初始化变量
cap = None
camera_running = False
# 获取可用摄像头列表
cameras = list_cameras()
if not cameras:
messagebox.showerror("Error", "未找到摄像头")
root.destroy()
else:
# 创建下拉菜单
camera_combobox = ttk.Combobox(root, values=[f"Camera {i}" for i in cameras], state="readonly")
camera_combobox.grid(row=0, column=0, padx=10, pady=10)
camera_combobox.current(0) # 设置默认选择第一个摄像头
# 创建启动按钮
start_button = tk.Button(root, text="直播", command=on_start_button_click)
start_button.grid(row=0, column=1, padx=10, pady=10)
# 运行主循环
root.mainloop()
09-15
3211
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
02-13
7154
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
03-26
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交