我想制作一个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&GT;
python TestWeb1.p y
回溯(最近一次调用最后一次):文件&#34; TestWeb1.py&#34;,第12行,在screenTake = tk.Button(text =&#39; ScreenShot&#39;,command = TakePictureC)#The对拍拍照
NameError:name&#39; TakePictureC&#39;未定义
答案 0 :(得分:1)
如果您看到错误消息(“追溯”),则应完整显示(复制并粘贴)。
这一行:
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。