繁体   English   中英

Python 2.7 Tkinter用CV2拍照

[英]Python 2.7 Tkinter Take Photo with CV2

我想用Python 2.7 Tkinter拍摄网络摄像头照片,但我无法解决问题:我的程序不想读取变量并执行它。 你能帮助我吗?

这是我的代码:

import Tkinter as tk
import cv2
from PIL import Image, ImageTk

width, height = 800, 600    #Initialisation of webcam size
cap = cv2.VideoCapture(0)   #Type of Capture

takePicture = 0 #My variable

lmain = tk.Label()  #The Tk widget of webcam
lmain.pack()    #Pack option to see it
screenTake = tk.Button(text='ScreenShot' ) , command = TakePictureC) #The button for take picture
screenTake.pack()   #Pack option to see it

def TakePictureC(): #There is the change of the variable

    takePicture  = takePicture + 1 #Add "1" to the variable

def show_frame(): #CV2 webcam parameters
_, frame = cap.read()
frame = cv2.flip(frame, 1)
cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
img = Image.fromarray(cv2image)
imgtk = ImageTk.PhotoImage(image=img)
lmain.imgtk = imgtk
lmain.configure(image=imgtk)
lmain.after(10, show_frame)

if takePicture == 1: #My option for take the image
    img.save("test.png") #Save the instant image
    takePicture  = takePicture - 1 #Remove "1" to the variable

show_frame() #CV2 show the webcam module
root = tk.Tk()                                  #basic parameters
root.bind('<Escape>', lambda e: root.quit())
root.title( "title" )
root.mainloop()                                 #end of the program

谢谢您的帮助,祝您度过一个愉快的星期。(对不起,我的英语不好,我是法国学生:/)

我的错误讯息:

C:\\用户*** \\桌面\\ Programmations \\的Python编程\\ PyStoMo>

python TestWeb1.py

追溯(最近一次通话):文件“ TestWeb1.py”,第12行,在screenTake = tk.Button(text ='ScreenShot',command = TakePictureC)#用于拍照的按钮

NameError:名称“ TakePictureC”未定义

如果看到错误消息(“回溯”),则应完整显示(复制并粘贴)。

这行:

screenTake = tk.Button(text='ScreenShot' ) , command = TakePictureC) #The button for take picture

的')'太多。 它应该是:

screenTake = tk.Button(text='ScreenShot', command = TakePictureC) #The button for take picture

接下来,在函数内部,如果您分配了名称,则除非另有说明,否则它将假定该名称是本地名称,因此在尝试运行此函数时:

def TakePictureC(): #There is the change of the variable

    takePicture  = takePicture + 1 #Add "1" to the variable

它会引发一个NameError。

应该是:

def TakePictureC(): #There is the change of the variable
    global takePicture
    takePicture  = takePicture + 1 #Add "1" to the variable

最后,函数“ show_frame”的主体应缩进。

编辑:

您的追溯说:

NameError: name 'TakePictureC' is not defined

那是因为该行:

screenTake = tk.Button(text='ScreenShot', command = TakePictureC)

表示单击底部时调用TakePictureC,但尚未定义TakePictureC。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM